[英]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. 例如,“ timer”及其相反的“ remit”都在小写单词列表中。
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 . 只需使用[::-1]
,这里就不需要使用list(),并且list(word).reverse()
返回None
因为它就地更改了列表。 You can also use "".join(reversed(word))
, but I guess just word[::-1]
is simple enough: 您也可以使用"".join(reversed(word))
,但是我想word[::-1]
就足够简单了:
[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. list.reverse()
方法可将列表原地反向。 Its return value is None
. 它的返回值为None
。 If you want to reverse a string just use word[::-1]
. 如果要反转字符串,请使用word[::-1]
。
list.reverse()
reverses the list in place and returns nothing. list.reverse()
在原处反转列表,但不返回任何内容。 You need "".join(reversed(list))
. 您需要"".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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.