python - 如何从单词列表转到 Python 中不同字母的列表

标签 python filter distinct list-comprehension letters

我试图使用 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/

相关文章:

python - 在 Python 中将对象标记为已删除

python - 使用 BeautifulSoup 刮页面

python - R 相当于 python 的 os.getpid() 用于并行处理

php - WordPress 画廊问题

python - 如何在 Python 3 中使用过滤器、映射和归约

Python Linux DNS 别名和地址回复

c# - 你能用 lambda 表达式创建一个简单的 'EqualityComparer<T>' 吗

SQL查询在两个表中查找不同的值?

mysql 在选择中选择不同的

swift - 我过滤了字典的 NSMutableArray 然后我想再次过滤一个键