不重复的变化

2024-04-19 19:04:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Formula 我一直在寻找有效的方法来检查列表中k元素的sum是否等于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 = []

这对于大名单的随机选择是不有效的。在


Tags: 方法importnumpy元素示例列表图书馆random
1条回答
网友
1楼 · 发布于 2024-04-19 19:04:52

我想这是你需要的

from itertools import combinations

l = [1, 0, 1, 3, 4, 2, 2]
x = 10

for i in range(len(l)):
    for c in combinations(l, i):
        if sum(c) == x:
            print(c)

相关问题 更多 >