Reputation: 3
I have 2D list and I am trying to find the occurrence of the word 'the' in the list.
I am self learning python and try the following code
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)
I am expecting a result of 4 but the program return 0.
Upvotes: 0
Views: 343
Reputation: 16
Look for the elements of the two different arrays. Try this:
whatIsTheSum = sum('the' in s for s in data[0]+data[1])
print(whatIsTheSum)
Upvotes: 0
Reputation: 2887
Because you didn't iterate over the nested array
whatIsTheSum = sum('the' in s for nested in data for s in nested)
Upvotes: 2