[英]what's the difference between these 2 python codes? why different results?
[英]what is the difference between these 2 python codes, and why the out put is not same?
这些是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}
在我的观点中,w 是单词中的单词,所以w应该等于words ,但是 output 是不同的。 有人可以帮助我,为什么 output 不同?
如果words
是{'abba', 'abcd', 'dcba'}
那么第一个代码的结果将是{'abba', 'abcd', 'dcba'}
而第二个将返回{'abba'}
。
w==w[::-1]
检查单词是否等于它的反向,而w[::-1] in words
检查w
的反向是否在words
中。
我猜那些代码 sanples 正在做不同的事情。
{w for w in words if w[::-1] in `words` and len(w)==4}
它包括来自可迭代words
的元素w
,如果只有反转的w
("ABCD" => "DCBA") 也出现在words
中并且它的长度是 4。
{w for w in words if w==w[::-1]and len(w)==4}
这包括words
中的元素w
如果只有w
等于反转w
本身(“abba”=“abba”)并且它的长度是 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.