python - 如何在列表理解期间检查列表的条件?

标签 python list-comprehension python-3.6

假设我有一个包含三个单词的列表,我想生成一个包含该单词中的字符的列表。

这可以使用 for 循环或列表理解轻松实现:

wordList = ["one", "two", "three"]
letterList = []

# Solution 1:

for word in wordList:
    for letter in word:
        letterList.append(letter)

# Solution 2:

letterList = [letter for word in wordList for letter in word]

print(letterList) # Prints: ['o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e']

但是,当这个问题变得更加困难时,我无法使用列表理解找到解决方案。

例如,假设我想生成之前的列表,但我还希望删除所有重复的字符。

我可以使用 for 循环来做到这一点:

wordList = ["one", "two", "three"]
letterList = []

for word in wordList:
    for letter in word:
        if letter not in letterList:
            letterList.append(letter)

print(letterList) # Prints: ['o', 'n', 'e', 't', 'w', 'h', 'r']

所以,我的问题是:如何检查某个项目是否在列表理解期间正在构建的列表中?或者更简单地说:如何使用列表推导式执行上述操作?

最佳答案

在 Python 3.6 中,字典是有序的。因此,您可以使用字典理解:

>>> list({letter:None for word in wordList for letter in word}.keys())
['o', 'n', 'e', 't', 'w', 'h', 'r']

从 Python 3.7 开始,将保证顺序:

python news: 😀 @gvanrossum just pronounced that dicts are now guaranteed to retain insertion order. This is the end of a long journey. source (2017-12-15)

关于python - 如何在列表理解期间检查列表的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996671/

相关文章:

python - 如何在 pydot 中的两个子图之间添加边?

python - 我如何在 Django 中实现合并查询?

python - (Python/Django) : How do I keep my production db in sync (scheme and data) and with dev pc db?

python - 尝试从文本文件创建字典

python - python 中的映射函数在解包值时抛出错误

python:循环的单线笛卡尔积

Python错误: 'None Type' object does not support item assignment

python - MySQL-python 安装无法在 virtualenv 中运行

python - 为ios创建数据库

python-requests - 这是python36版本问题吗?如何解决?