我一直在寻找有效的方法来检查列表n中k元素的总和是否等于x值。我认为也许在 numpy 和 intertools 库中会有所帮助。
例子:
list = [1, 0, 1, 3, 4, 2, 2]
temp = list.copy()
x = 10
result = []
import random
while sum(result) != x:
try:
a = random.choice(temp)
result.append(a)
temp.remove(a)
except IndexError:
temp = list.copy()
result = []
if sum(result) > 10:
result = []
这对于大列表的随机选择效率不高。