在python中搜索和替换2D数组中的元素

时间:2017-09-06 16:02:27

标签: python arrays multidimensional-array

我试图找出一种方法来搜索2D数组以找到某个单词然后替换该单词。

例如:

pets = [['I', 'have', 'a', 'cat'], ['She', 'has', 'a', 'pet', 'cat']]

我需要一种搜索​​单词“cat'并将其替换为“狗”字样。

2 个答案:

答案 0 :(得分:4)

您可以使用列表推导检查所有元素,并将'cat'替换为'dog'

pets = [['I', 'have', 'a', 'cat'], ['She', 'has', 'a', 'pet', 'cat']]

new_pets = [[p if p.lower()!='cat' else 'dog' for p in s] for s in pets]
print(new_pets) # => [['I', 'have', 'a', 'dog'], ['She', 'has', 'a', 'pet', 'dog']]

答案 1 :(得分:0)

使用list comprehension

pets = [[val.replace('cat', 'dog') for val in row] for row in pets]
相关问题