python - 具有嵌套循环和 if 条件的列表理解,以及新列表的成员资格

标签 python algorithm loops if-statement list-comprehension

这是带有 if 条件和新列表成员资格的常规嵌套循环:

wordlist = ["micro", "macro", "stats"]
letterlist = []

for aword in wordlist:
    for aletter in aword:
        if aletter not in letterlist:  
            letterlist.append(aletter)
print(letterlist)

打印出的字母没有重复:['m', 'i', 'c', 'r', 'o', 'a', 's', 't']

当我尝试使用列表理解来做同样的事情时,我只能通过嵌套循环:

wordlist = ["micro", "macro", "stats"]
letterlist = [aletter for aword in wordlist for aletter in aword]
print(letterlist)

这会打印出所有重复的字母:['m', 'i', 'c', 'r', 'o', 'm', 'a', ' c', 'r', 'o', 's', 't', 'a', 't', 's']

不幸的是,这不起作用:

wordlist = ["micro", "macro", "stats"]
letterlist = [[if aletter not in letterlist] for aword in wordlist for aletter in aword]

问题:如何根据上面的示例使用列表推导式执行 perform the neSTLoop with if 语句?

提前致谢

最佳答案

您可以使用函数 dict.fromkeys()chain.from_iterable():

from itertools import chain

list(dict.fromkeys(chain.from_iterable(wordlist)))
# ['m', 'i', 'c', 'r', 'o', 'a', 's', 't']

在 Python 3.6 及以下版本中,您需要将 dict 替换为 OrderedDict

关于python - 具有嵌套循环和 if 条件的列表理解,以及新列表的成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212769/

相关文章:

java - 我应该如何递归地编写这个Java函数?

python - 如何更改 Pandas 图中 fiddle 图的边框颜色?

python - 将一系列数字更改为列表,python

c - 四叉树效率中的范围搜索

java - MySQL - 遍历结果集中的列

java - Struts2 使用动态变量通过列表进行嵌套迭代

python - distutils setup install --build-base 不起作用

python - 编写一个简单的 Python 程序

c# - 确定电梯总停靠次数的程序

php - 获取二维数组相对于一维数组大小的维度