如何在Python中将单词列表转换为不同字母列表
我正在用Python尝试把一句话中的所有不同字母提取成一个简单的列表。
这是我现在的代码:
words = 'She sells seashells by the seashore'
ltr = []
# Convert the string that is "words" to a list of its component words
word_list = [x.strip().lower() for x in words.split(' ')]
# Now convert the list of component words to a distinct list of
# all letters encountered.
for word in word_list:
for c in word:
if c not in ltr:
ltr.append(c)
print ltr
这段代码返回了['s', 'h', 'e', 'l', 'a', 'b', 'y', 't', 'o', 'r']
,结果是对的,但有没有更“Python风格”的方法来得到这个结果,可能可以用列表推导式或者set
?
当我尝试把列表推导式和过滤结合起来时,得到的却是列表的列表,而不是一个简单的列表。
最终列表中不同字母的顺序(ltr
)并不重要;关键是这些字母必须是独一无二的。
7 个回答
3
set([letter.lower() for letter in words if letter != ' '])
编辑: 我刚刚试了一下,发现这样也可以用(也许这就是SilentGhost提到的意思):
set(letter.lower() for letter in words if letter != ' ')
如果你需要一个列表而不是一个集合,你可以
list(set(letter.lower() for letter in words if letter != ' '))
3
把 ltr
变成一个集合,然后稍微修改一下你的循环内容:
ltr = set()
for word in word_list:
for c in word:
ltr.add(c)
或者可以用列表推导式来实现:
ltr = set([c for word in word_list for c in word])
13
集合提供了一种简单而高效的解决方案。
words = 'She sells seashells by the seashore'
unique_letters = set(words.lower())
unique_letters.discard(' ') # If there was a space, remove it.