python - 从重复元素列表中创建非重复元素列表。仅使用列表理解
问题描述
如何将下面的这个“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']
推荐阅读
- javascript - 默认禁用谷歌浏览器扩展
- python - 如何阻止python在特定虚拟环境中安装模块并全局安装?
- c - 后缀表达式 - 检查空格
- python - 我无法使用自定义模型管理器访问模型的属性
- android - Flutter VSCode 无法在真机上运行
- python - 根据元数据重命名 mp3 文件
- regex - 使用 .htaccess 将自定义图像 url 重写到目录
- python - 如何在 scikit-learn 中计算回归成本函数
- javascript - 投影在节点 js 中不起作用的字段
- amazon-redshift - 如何从 Redshift 获取描述表并更改它