繁体   English   中英

根据相应的字典值转换列表的元素

[英]Converting elements of a list based on corresponding dictionary values

我试过用谷歌搜索,但谷歌结果只是告诉我如何将列表转换为字典,这不是我想要做的。

我有一个清单: colors = ['Red', 'White', 'Green', 'Red']

我有一本字典: color_dict = {'Red': 0, 'White': 1, 'Green': 2}

我想以converted_colors = [0, 1, 2, 0]结尾

我试过converted_colors = [color for colors in color_dict[color]]converted_colors = [color for color_dict[color] in colors]

但两者都给出相同的错误NameError: name color is not defined

我的方法全错了吗? 任何帮助将非常感激。

这里有一个例子

converted_colors = [color_dict[color] for color in colors]

这里是 output

 [0, 1, 2, 0]

这是另一种方法

colors = ['Red', 'White', 'Green', 'Red'] color_dict = {'Red': 0, 'White': 1, 'Green': 2} converted_colors = [] for i in colors: converted_colors.append(color_dict[i]) print(converted_colors)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM