创建可能组合列表的列表

2024-05-15 04:22:56 发布

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

我有一份清单,其中包含以下项目:

initl = [1, 2, 3, 4]

stepsize,即stepsize = 0.05。列表中的每个值都允许stepsize向上或向下更改。我想创建的是一个列表列表,其中包含向上、向下或初始值的所有组合,例如:

result_list = [[1, 2, 3, 4], [1.05, 2, 3, 4], [0.95, 2, 3, 4], [1, 2.05, 3, 4], ...] 

列表中组合的顺序并不重要

我想到了这个:

import itertools


initl = [1, 2, 3, 4]
stepsize = 0.05

lu = [i + stepsize for i in initl]
ld = [i - stepsize for i in initl]

l_map = list(itertools.product(range(3), repeat=4))

result_list = []

for i in l_map:
    l_new = []
    for pos, j in enumerate(i):
        if j == 0:
            l_new.append(ld[pos])
        elif j == 1:
            l_new.append(initl[pos])
        else:
            l_new.append(lu[pos])
   result_list.append(l_new)

它产生所需的输出。列表长度:3^4=81。 但我想知道是否有更好的方法。这里嵌套的for循环对我来说特别笨重。谢谢你的帮助


Tags: 项目inposmap列表newforresult
3条回答

您可以尝试如下列表理解:zip使用initlproduct进行理解:

>>> from itertools import product
>>> initl = [1, 2, 3, 4]
>>> step = [-0.05, 0, 0.05]
>>> [[x+d for x, d in zip(initl, p)] for p in product(step, repeat=len(initl))]
[[0.95, 1.95, 2.95, 3.95],
 [0.95, 1.95, 2.95, 4],
 ...
 [1.05, 2.05, 3.05, 4.05]]
>>> len(_)
81

尝试:

def getComb(arr, step, res=[]):
    if(len(arr)==1):
        for el in [-step, 0, step]:
            yield res+[arr[0]+el]
    else:
        for el in [-step, 0, step]:
            yield from getComb(arr[1:], step, res+[arr[0]+el])

对于您的输入数据输出:

>>> for el in getComb(initl, stepsize): print(el)

[0.95, 1.95, 2.95, 3.95]
[0.95, 1.95, 2.95, 4]
[0.95, 1.95, 2.95, 4.05]
[0.95, 1.95, 3, 3.95]
[0.95, 1.95, 3, 4]
...
[1.05, 2.05, 3, 4]
[1.05, 2.05, 3, 4.05]
[1.05, 2.05, 3.05, 3.95]
[1.05, 2.05, 3.05, 4]
[1.05, 2.05, 3.05, 4.05]

您的想法是正确的,基本上是自己实现^{},用于一个3选择的案例

您可以直接在包含每个值的所有选项元组的列表上使用itertools.product进行简化,如下所示:

import itertools

initl = [1, 2, 3, 4]
stepsize = 0.05

prod_seed = [(i, i+stepsize, i-stepsize) for i in initl]
result_list = list(itertools.product(*prod_seed))

print(result_list)
print(len(result_list))

输出:

[(1, 2, 3, 4), (1, 2, 3, 4.05), (1, 2, 3, 3.95), ....]
81

相关问题 更多 >

    热门问题