簡體   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