如何将下面的这个“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]
您可以set
在 python 中使用它表示唯一元素的无序集合。
采用:
colors = list(set(many_colors))
print(colors)
这打印:
['red', 'black', 'blue']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句