簡體   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