Python二维列表中查找字符串出现次数:代码返回0而非预期4
Hey there! Let's figure out why your code is returning 0 instead of the expected 4.
The issue here is that your current loop is iterating over the outer list elements (which are the two sublists in data), not the individual strings inside those sublists. When you check 'the' in s where s is a sublist like ["the cat is fed", ...], it's checking if the string 'the' is an element of that sublist—which it isn't, hence all those checks return False, and summing them gives 0.
To fix this, you need to iterate through each sublist first, then iterate through each string in those sublists. Here are a couple of ways to do it:
Option 1: Nested generator expression (cleanest)
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 sublist in data for s in sublist) print(whatIsTheSum) # Output: 4
This works because we first loop over each sublist in data, then loop over each string s in that sublist, checking if 'the' is present in each string. The generator expression produces True (treated as 1) or False (treated as 0) for each check, and sum() adds them all up.
Option 2: Explicit nested loops (more verbose but clear)
If you prefer a more explicit approach, you can use nested for loops to count manually:
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"]] count = 0 for sublist in data: for s in sublist: if 'the' in s: count += 1 print(count) # Output: 4
Both approaches will correctly count all 4 occurrences of the string 'the' in your data. Just remember—when dealing with nested lists, you need to go one level deeper to access the actual strings you want to check!
内容的提问来源于stack exchange,提问作者gunwinger

