简体   繁体   中英

how to count number of elements in a list in a list?

This might be pretty simple but my program is just a movie ticket booking:

My list is (for example):

bookings=[["Sam", 1, "titanic", "morning", "Stit1"],
          ["Bill", 2, "titanic", "evening", "Btit2"],
          ["Kik", 2, "lionking", "afternoon", "Klio2"]] 

I want to print how many people are (for example) going to watch titanic. How do I do that?

Thanks in advance

Try

sum(b[2] == 'titanic' for b in bookings)

This creates a generator over bookings , then sums those with "titanic".

Note the implicit treatment of True and False as 1 and 0, respectively.

You want only number or names also? Anyway, like this you getting list with all the people who going to watch 'Titanic' and you can easily get length of it

bookings=[["Sam", 1, "titanic", "morning", "Stit1"], ["Bill", 2, "titanic", "evening", "Btit2"], ["Kik", 2, "lionking", "afternoon", "Klio2"]]
count = [item for item in bookings if 'titanic' in item]
print(len(count))

You can create a dictionary with movie names as keys and value being the total count. Something like this


ticket_count = {}
for booking in bookings:
    ticket_count[booking[2]] = ticket_count.get(booking[2], 0) + 1

I am assuming that movie name is always third element in the list.

You can do a sum of 1 for each relevant booking.

Only the third field is relevant in deciding which bookings to include, so you should use it (ie booking[2] here). If you look indiscriminately at all of the elements, then it might happen to work in most cases, but you could encounter problems if the movie name also appears in a different field, eg Morning (film) .

The following method does not rely on performing arithmetic using boolean values.

sum(1 for booking in bookings if booking[2] == "titanic")

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