[英]what is the difference between these 2 python codes, and why the out put is not same?
these are the 2 python3 code,这些是2个python3代码,
{w for w in words if w[::-1] in words and len(w)==4}
{w for w in words if w==w[::-1]and len(w)==4}
In my point, w is the word in words, so w should equal with words ,but the output is differently.在我的观点中,w 是单词中的单词,所以w应该等于words ,但是 output 是不同的。 Could someone help me, why the output is different?有人可以帮助我,为什么 output 不同?
if words
is {'abba', 'abcd', 'dcba'}
then the result of the first code will be {'abba', 'abcd', 'dcba'}
while the second will return {'abba'}
.如果words
是{'abba', 'abcd', 'dcba'}
那么第一个代码的结果将是{'abba', 'abcd', 'dcba'}
而第二个将返回{'abba'}
。
w==w[::-1]
checks if the word is equal to its reverse while w[::-1] in words
checks if the reverse of w
is in words
. w==w[::-1]
检查单词是否等于它的反向,而w[::-1] in words
检查w
的反向是否在words
中。
I guess those code sanples are doing really different things.我猜那些代码 sanples 正在做不同的事情。
{w for w in words if w[::-1] in `words` and len(w)==4}
It includes element w
from itterable words
if only reversed w
("ABCD" => "DCBA") is also present at words
and it's length is 4.它包括来自可迭代words
的元素w
,如果只有反转的w
("ABCD" => "DCBA") 也出现在words
中并且它的长度是 4。
{w for w in words if w==w[::-1]and len(w)==4}
This includes element w
from words
if only w
is equal to reversed w
itself ("abba" = "abba") and it's length is 4这包括words
中的元素w
如果只有w
等于反转w
本身(“abba”=“abba”)并且它的长度是 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.