【发布时间】:2020-04-16 12:15:13
【问题描述】:
如何将下面的“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]
【问题讨论】:
-
顺序重要吗?
-
您正在创建
colors,这也意味着您不应在实际创建之前引用它。
标签: python python-3.x list list-comprehension non-repetitive