繁体   English   中英

检查列表或项目组合中有多少项目与条件匹配的Python方法

[英]Pythonic way to check how many items in a list or combination of items match a condition

说我有一个这样的清单:

l = [20,17,8,7,4,9]

我想检查有多少项目或项目组合符合价值条件。

要检查单个项目,可以这样做:

minimum_value = 12
count = 0
for item in l:
    if item >= minimum_value:
        count += 1

但我也想检查该列表的组合。 那么计数将为4:20、17、9 + 4、8 + 7

我该怎么办?

您可以通过在每次迭代中检查总值来做到这一点。 如果总数大于最小值,请增加计数并重置总数。 否则,将下一次迭代中的数字加到总数中,然后再次检查。

l = [20,17,8,7,4,9]

minimum_value = 12
count = 0
sum = 0
for item in l:
    sum += item
    if sum >= minimum_value:
        count += 1
        sum = 0

print(count)

如果我理解您的问题,则要对照一个最小值检查所有值以及所有值组合,然后返回此类计数。 以下代码将执行此操作。

注意:执行此操作的方法可能更简洁,但是我认为这是最容易阅读的方法。

l = [20, 17, 8, 7, 4, 9]
minimum_value = 12
count = 0

newl = [] # Create a new list to store all the different combinations
for i in range(len(l)): # Get each index in l
    newl.append(l[i]) # Append the value at the current index to newl
    for n in l[i+1:]: # Loop through the remaining numbers starting at index + 1
        newl.append(l[i] + n) # Combine

count = len([x for x in newl if x >= minimum_value])  # Get the length of a list generated by taking all numbers in newl that are >= minimum_value
print(count)

在上述情况下, newl包含: [20, 37, 28, 27, 24, 29, 17, 25, 24, 21, 26, 8, 15, 12, 17, 7, 11, 16, 4, 13, 9] newl [20, 37, 28, 27, 24, 29, 17, 25, 24, 21, 26, 8, 15, 12, 17, 7, 11, 16, 4, 13, 9]

因此有16值超过了12minimum_value

暂无
暂无

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

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