在python中的2D列表中搜索出现的事件

时间:2019-06-09 15:05:00

标签: python-3.x

我有2D列表,并且试图在列表中查找单词“ the”的出现。

我正在自学python,请尝试以下代码

data = [["the cat is fed", "the bar is barred", "cat is now a bar"],
        ["the cat was fed", "the bar was barred", "cat was now a bar"]]

whatIsTheSum = sum('the' in s for s in data)

print(whatIsTheSum)

我期望结果为4,但程序返回0。

2 个答案:

答案 0 :(得分:2)

因为您没有遍历嵌套数组

ENDIF

答案 1 :(得分:0)

查找两个不同数组的元素。试试这个:

whatIsTheSum = sum('the' in s for s in data[0]+data[1])
print(whatIsTheSum)