Why is list count not working as I expect with nested lists?

90
March 23, 2022, at 03:40 AM

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
Answer 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
Answer 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]))
Answer 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
Rent Charter Buses Company
READ ALSO
Iterate through Python for loop more quickly

Iterate through Python for loop more quickly

I have a Pandas data frame (called "ud_flex" below) that looks like the one below: The data frame has over 27 million observations in it that I'm trying to iterate through to do a calculation for each rowBelow is the calculation that I'm using:

122
how check python wrote package version automatically?

how check python wrote package version automatically?

How to check current running package and module version automatically based on something like hash, git(uncommitted is also required), change file date?

94
How to update Tweepy Streaming Python code

How to update Tweepy Streaming Python code

I had this code running for an earlier version of Python but now want to upgrade it to the latest version of Python and Tweepy however I cant seem to make it workAny help would be much appreciated! The error I get is:

174
How to make a request in an API only when some data changes?

How to make a request in an API only when some data changes?

I'm using an API and I'm running the requst like this:

89