Python根据另一个列表修改一个列表

时间:2019-05-01 18:41:06

标签: python list

我有一个列表:     my_colors = ['blue', 'blue', 'blue', 'red', 'red', 'green']

我有一个“有效”列表:     valid_colors = ['red', 'white', 'blue']

如何删除列表中不在有效列表(valid_colors)中的所有项目?这样我得到:my_colors = ['blue', 'blue', 'blue', 'red', 'red'](没有绿色)

2 个答案:

答案 0 :(得分:1)

您可以像这样使用列表理解来重新创建my_colors

my_colors = [color for color in my_colors if color in valid_colors]

答案 1 :(得分:0)

my_colors = ['blue', 'blue', 'blue', 'red', 'red', 'green']
valid_colors = ['red', 'white', 'blue']

[如果v在有效颜色中,则v在my_colors中为v]

  

['blue','blue','blue','red','red']