简体   繁体   中英

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

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

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]))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM