简体   繁体   English

如何计算列表中列表中元素的数量?

[英]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".这将创建一个基于bookings的生成器,然后将这些与“泰坦尼克号”相加。

Note the implicit treatment of True and False as 1 and 0, respectively.注意TrueFalse的隐式处理分别为 1 和 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))

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.您可以为每个相关预订进行总计1

Only the third field is relevant in deciding which bookings to include, so you should use it (ie booking[2] here).只有第三个字段与决定包含哪些预订相关,因此您应该使用它(即此处的booking[2] )。 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) .如果您不加选择地查看所有元素,那么在大多数情况下它可能会起作用,但是如果电影名称也出现在不同的字段中,例如Morning (film) ,您可能会遇到问题。

The following method does not rely on performing arithmetic using boolean values.以下方法不依赖于使用布尔值执行算术。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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