我试图使用 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
) 中不同字母的顺序并不重要;重要的是它们是独一无二的。
最佳答案
集合提供了一种简单、高效的解决方案。
words = 'She sells seashells by the seashore'
unique_letters = set(words.lower())
unique_letters.discard(' ') # If there was a space, remove it.
关于python - 如何从单词列表转到 Python 中不同字母的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2245903/