列表python的列表排列

2024-09-27 02:17:59 发布

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

我想要我所有的列表排列和组合,我用itertools.product来计算排列,但是我的计算机无限期挂起,我可能做错了什么?在

import itertools

#Lists of all the possible dimensions
upperchest_dim=range(32,52,1)
upperback_dim=range(32,52,1)
chest_dim=range(32,52,1)
waist_dim=range(32,52,1)
hip_dim=range(32,52,1)
bicep_dim=range(32,52,1)
elbow_dim=range(32,52,1)
thigh_dim=range(32,52,1)
knee_dim=range(32,52,1)
calf_dim=range(32,52,1)
height_dim=range(32,52,1)

#List of lists total
dimensions=[upperchest_dim,upperback_dim,chest_dim,waist_dim,hip_dim,bicep_dim,elbow_dim,thigh_dim,knee_dim,calf_dim,height_dim]

#Generate permutations of all the dimensions
print list(itertools.product(*dimensions))

list(itertools.product(*dimensions))应该具有所有维度可能的唯一置换。在

在-- 编辑: 我想我做错了什么。我想要一个包含所有唯一维度的列表列表,例如[32,33,34,45,34,23,42,43,43,45,33]这是一个维度,结果不应该再包含这个确切的列表,因为它代表一种身体类型。在


Tags: ofthe列表rangeallproductdimensionsitertools
3条回答

不需要所有这些东西,您只需使用permutations

from itertools import permutations

var = permutations([12, 34, 123, 12, 31, 231])

for perm in var:
    print perm

甚至可以处理list的列表:

^{pr2}$

工作example。在

如果出于某种原因,您想要所有可能的排列,甚至是列表中列表的排列,则必须使用以下代码:

from itertools import permutations

var = [[1, 2, 3, 4], [24, 5, 12, 3], 123, 12, 31, 231]

# Getting all permutations of lists within the lists
output = []
for l in var:
    if isinstance(l, list):
        output += permutations(l)
    else:
        output.append(l)

perm = permutations(output)

for p in perm:
    print p

正在工作example。在

如果你在最后一行

for d in itertools.product(*dimensions): print(d)

开始打印了

... (32, 32, 32, 32, 32, 32, 32, 33, 37, 47, 45) (32, 32, 32, 32, 32, 32, 32, 33, 37, 47, 46) (32, 32, 32, 32, 32, 32, 32, 33, 37, 47, 47) (32, 32, 32, 32, 32, 32, 32, 33, 37, 47, 48) ...

所以“没什么”是错的,结果列表太大了,不能一次计算

该列表将包含20**11=2**11*10**11=20480000000000个元素。这就是问题所在。在

尽管itertools.product是一个不会无限期挂起的迭代器(只需要花很长时间来遍历它),将它转换为list()将挂起,直到它使用完所有内存。在

相关问题 更多 >

    热门问题