简体   繁体   中英

what is the difference between these 2 python codes, and why the out put is not same?

these are the 2 python3 code,

{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. Could someone help me, why the output is different?

if words is {'abba', 'abcd', 'dcba'} then the result of the first code will be {'abba', 'abcd', 'dcba'} while the second will return {'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 .

I guess those code sanples are doing really different things.

{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.

{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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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