首页 > 解决方案 > 从重复元素列表中创建非重复元素列表。仅使用列表理解

问题描述

如何将下面的这个“for-loop”转换为“list-comprehension?我想从重复元素列表中创建一个非重复元素的列表。

many_colors = ['red', 'red', 'blue', 'black', 'blue']

colors = []
for c in many_colors:
  if not c in colors:
    colors.append(c)
# colors = ['red', 'blue', 'black']

我尝试了这个(下),但发生了未定义颜色的错误。

colors = [c for c in many_colors if not c in colors]

标签: pythonpython-3.xlistlist-comprehensionnon-repetitive

解决方案


您可以set在 python 中使用它表示唯一元素的无序集合。

利用:

colors = list(set(many_colors))
print(colors)

这打印:

['red', 'black', 'blue']

推荐阅读