首页 > 解决方案 > 用Python中的多个条件替换数组中的字符串值

问题描述

我有一个数组: array = ['wood', 'glass', 'metal', 'glass', 'glass', 'wood', 'metal', 'wood', 'glass', 'glass']

我想用一个条件替换每个字符串,例如:每个'wood'替换为'blue''glass'by'red''metal'by 'green'

所以我得到: ['blue', 'red', 'green', 'red', 'red', 'blue', 'green', 'blue', 'red', 'red']

我正在尝试做类似的事情: ['red' if el == 'glass' for el in array]

我不知道如何做多个条件,或者即使这种方法是正确的做法?

请帮忙 :)

标签: pythonarrays

解决方案


您可以使用字典将旧值映射到新值。

例子:

>>> name_mapping = {'wood':'blue'}
>>> res = [name_mapping.get(el, el) for el in array]
>>> res
['blue', 'glass', 'metal', 'glass', 'glass', 'blue', 'metal', 'blue', 'glass', 'glass']

dict.get将当前元素保留在结果中,以防该元素不是映射字典的键。


推荐阅读