python - 用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]
我不知道如何做多个条件,或者即使这种方法是正确的做法?
请帮忙 :)
解决方案
您可以使用字典将旧值映射到新值。
例子:
>>> 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将当前元素保留在结果中,以防该元素不是映射字典的键。
推荐阅读
- c# - 使用“Visual Studio 安装程序”创建的安装程序安装应用程序后未打开应用程序
- math - 天才数学工具:如何将分数答案显示为小数?
- javascript - 字形完全渲染后如何调用 JS 函数或 Python 方法?
- python - 如何编辑类的实例?
- r - 使用 ggplot 2 突出显示几个特定点
- c# - 查看已签署的协议时,有没有办法配置 DocuSign 的 UI?
- node.js - 在分叉的子进程中, process.exit() 在 await 函数完成之前执行
- python - 如何使用 ImageGrab.grab().load() 函数或任何其他函数来获取像素更新?
- mysql - 有没有办法比较两个创建表查询并通过添加新列来更改现有表?
- reactjs - 如何在打字稿中使用反应安全地定义 HTMLCollectionOf 元素?