繁体   English   中英

这两个 python 代码有什么区别,为什么输出不一样?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM