繁体   English   中英

用 Python 中的多个条件替换数组中的字符串值

[英]Replace string values in array by multiple conditions in Python

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

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

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

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

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

请帮忙:)

您可以使用字典将 map 旧值转换为新值。

例子:

>>> 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将当前元素保留在结果中,以防该元素不是映射字典的键。

也许创建一个字典:

dct = {'wood': 'blue', 'glass': 'red', 'metal': 'green'}
new_array = [dct[item] for item in array] 

暂无
暂无

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

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