0

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

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think that in view of what is going on "under the hood" here, it would be worth saying some more about how this works, in terms of how True and False boolean values are treated in integer arithmetic.
0

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

Comments

0

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.

Comments

0

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 (i.e. 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, e.g. Morning (film).

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.