简体   繁体   English

Python:如何在不使用 .count 的情况下计算列表列表的特定数量?

[英]Python: How can I count specific numbers of a list of lists without using .count?

I have a list of lists like this:我有一个这样的列表列表:

list = [["apple", "apple","bananas"], ["bananas, "apple", "bananas"], ["bananas","bananas","pear"]]

I want to know how many bananas do I have in each sub list.我想知道每个子列表中有多少根香蕉。 I want to obtain:我想获得:

number = [1],[2],[2]

I would like to achieve this using loops and condicionals and the minimum number of fancy funtions.我想使用循环和条件以及最少数量的花式函数来实现这一点。 I don't want to use.count, but.append would be ok.我不想使用.count,但是.append 就可以了。

I have tried this:我试过这个:

number = []
for cart in list:
    for fruit in range (0,len(cart)):
        if cart[fruit] == "banana":
            number.append("banana")
print(len(number))

But this only gives me the total number of bananas, not a list of fruit per cart.但这只给我香蕉的总数,而不是每车水果的清单。

What could I do?我能做什么? What am I doing wrong?我究竟做错了什么?

2-level list comprehension with sum()使用sum()的 2 级列表理解

mylist = [["apple", "apple","bananas"], ["bananas", "apple", "bananas"], ["bananas","bananas","pear"]]
number = [[sum([1 if 'banana' in y else 0 for y in x])] for x in mylist]
print(number)
number = []
for c in range(len(carts)):
    n = 0
    for fruit in carts[c]:
        if fruit == "banana":
            n += 1
    number.append(n)

print(sum(number))

Since you would like to achieve this using a minimum number of fancy functions, I have coded it with just list.append() and loop nesting.由于您想使用最少数量的奇特函数来实现此目的,因此我仅使用list.append()和循环嵌套对其进行了编码。

carts = [["apple", "apple", "bananas"], ["bananas", "apple", "bananas"], ["bananas","bananas","pear"]]

banana_counts = []

for cart in carts:  
  count = 0
  for fruit in cart: # Using range() here is not Pythonic
    if fruit == 'bananas':
      count += 1
  banana_counts.append([count])

print(banana_counts) #[[1], [2], [2]]
number = [len([j for j in i if j=='banana']) for i in your_list]

explanation:解释:

[j for j in i if j=='banana'] # will result a list of only "banana"s from list "i" which is one element of source list

We create a list containing only "banana"s of each element in source list and then we get the length of these lists to get our desired result.我们创建一个仅包含源列表中每个元素的“香蕉”的列表,然后我们获取这些列表的长度以获得我们想要的结果。

len([cart for cart in carts if 'banana' in cart])

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

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