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