0

如何将下面的这个“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]
4

3 回答 3

0

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

利用:

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

这打印:

['red', 'black', 'blue']
于 2020-04-16T12:17:10.560 回答
-1

使用套装让您的生活更轻松:

colors = [c for c in set(many_colors)]
于 2020-04-16T12:16:49.023 回答
-1

colors只存在于理解完成之后。理解甚至可能不是最佳的。你可以做

colors = list(set(colors))

如果你想保持发生的顺序:

from collections import OrderedDict

colors = list(OrderedDict.fromkeys(many_colors))
于 2020-04-16T12:19:28.647 回答