我必须编写一个列表理解程序,以便用字符串列表中的字母组成一个列表,而不必重复字母。 例如:
words = ['cat', 'dog', 'rabbit']
应该返回
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
我首先使用嵌套的for循环,就像这样:
words = ['cat', 'dog', 'rabbit']
alphabets = []
for each_word in words:
for x in each_word:
if x not in alphabets:
alphabets.append(x)
print(alphabets)
现在我应该如何使用if语句将其转换为列表理解? 现在我可以做到这一点:
alphabets= [x for x in each_word for each_word in words]
返回
['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']
我需要这个为:
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
答案 0 :(得分:5)
列表推导应谨慎使用。他们很快就失控了。它们也不是用来改变状态的(在这种情况下为alphabets
)。
回答您的问题:
[alphabets.append(letter) or letter for word in words for letter in word if letter not in alphabets]
但是这很hacky,很糟糕。 不要这样做。
之所以有效,是因为append
返回None
,这使得or
返回下一个(或最后一个)值。甚至不用理会它。这是错误代码。
您可以这样做:
from itertools import chain
alphabets = set(chain.from_iterable(words))
相反。