【发布时间】:2011-01-15 19:08:33
【问题描述】:
使用 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'],这是正确的,但有没有更Pythonic的方式来回答这个问题,可能使用列表推导/set?
当我尝试将列表理解嵌套和过滤结合起来时,我得到的是列表列表而不是平面列表。
最终列表(ltr)中不同字母的顺序并不重要;关键是它们是独一无二的。
【问题讨论】:
-
+1 表示一个措辞恰当的问题并包含您的尝试(多么受欢迎的景象!)
-
请注意,
str.split默认在空格上分割,所以.split(' ')通常拼写为.split()。
标签: python filter distinct list-comprehension letters