'Why is list count not working as I expect with nested lists?
I can count simple list but can not count list of lists.
list1 = ['R', 'E', 'R', 'E']
print(list1[0])
print(list1.count(list1[0]))
My logic thinks if above is true below should be true, but I was wrong.
list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print(list1.count(list1[0][1]))
Output
R
2
R
0
Solution 1:[1]
If you're trying to count the total # of occurrences in your list of lists- you can add in a loop like this:
list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
check = list1[0][1] # R
count = 0
for list in list1:
count += list.count(check)
print(check)
print(count)
Output:
R
2
Solution 2:[2]
A string is not equal to a list containing that string, so list1.count('R') won't find any matches in the second snippet.
You can use a list comprehension to extract the [1] element of each nested list, and then count the matches there.
print([x[1] for x in list1].count(list1[0][1]))
Solution 3:[3]
Simply flatten the list with a nested list comprehension before counting its elements:
list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print([a for b in list1 for a in b].count(list1[0][1]))
Output:
R
2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mr_mooo_cow |
| Solution 2 | Barmar |
| Solution 3 | Ann Zen |
