简体   繁体   中英

Using sets in a list comprehension

what I am trying to do: Create and print a list of words for which the reverse of the word is in the set of lower-case words. For example, "timer" and its reverse, "remit", are both in the lower-case word list.

what i have so far:

     s = set(lowers)
     [word for word in s if list(word).reverse() in s]

i just get an empty list.

just use [::-1] , using list() is unnecessary here and list(word).reverse() returns None as it changes the list in-place . You can also use "".join(reversed(word)) , but I guess just word[::-1] is simple enough:

[word for word in s if word[::-1] in s]

In [193]: word="timer"

In [194]: print list(word).reverse()
None

In [195]: word[::-1]
Out[195]: 'remit'

In [196]: "".join(reversed(word))
Out[196]: 'remit'

The list.reverse() method reverses a list in place. Its return value is None . If you want to reverse a string just use word[::-1] .

list.reverse() reverses the list in place and returns nothing. You need "".join(reversed(list)) .

Try this:

s = set(lowers)
[word for word in s if word.lower()[::-1] in s]

您应该使用[::-1]反转字符串-

[word for word in s if word[::-1] in s]

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