修改包含Python3中集合的集合列表

问题描述 投票:0回答:2

我正在尝试创建一个以元组为元素的列表。每个元组都有4个整数。前2个整数是对2 ranges进行压缩的结果,而其他2对2个不同的整数进行压缩。

我正在使用此代码创建元组和最终列表,这些列表是从笛卡尔乘积派生的,如此处所示:Get the cartesian product of a series of lists?

import itertools
first_range = list(zip((10**exp for exp in range(0,7)),(10**exp for exp in range(1,8))))
second_range = list(zip((5*10**exp if exp != 1 else 10**2 for exp in range(1,8)),(5*10**exp for exp in range(2,9))))
final_list = list(itertools.product(first_range,second_range))

此代码的问题是最终结果看起来像这样:

[((1, 10), (100, 500)), ((1, 10), (500, 5000)), ((1, 10), (5000, 50000)), ((1, 10), (50000, 500000)), ((1, 10), (500000, 5000000)), ((1, 10), (5000000, 50000000)), ...

每个列表元素是一个包含2个其他元组的元组,而我想要的是这个:

[(1, 10, 100, 500), (1, 10, 500, 5000), (1, 10, 5000, 50000), (1, 10, 50000, 500000), (1, 10, 500000, 5000000), (1, 10, 5000000, 50000000), ...

即每个列表元素都是一个包含4个整数的元组。

任何想法都将不胜感激。必须在python3上工作。编辑:由于ShadowRanger的注释,更新了代码的无效部分

python python-3.x tuples cartesian-product
2个回答
0
投票

您的预期输出不是两个范围的笛卡尔积。

如果您希望获得预期的输出,类似这样的方法将起作用:

final_list = [(*x, *y) for x, y in zip(first_range, second_range)]

0
投票

因此,我确定一旦发布此问题,我就接近答案了,但是我没有意识到自己就这么接近。用额外的元组解决此问题的方法是:

import itertools
first_range = list(zip((10**exp for exp in range(0,7)),(10**exp for exp in range(1,8))))
second_range = list(zip((5*10**exp if exp is not 1 else 10**2 for exp in range(1,8)),(5*10**exp for exp in range(2,9))))
list_with_tuples = list(itertools.product(first_range,second_range))

# the next line solves my issue
final_list = [list_with_tuples[i][0] + list_with_tuples[i][1] for i in range(0,len(list_with_tuples))]

[我所做的是元组的简单合并:How to merge two tuples in Python?。不知道为什么我以前没想到

© www.soinside.com 2019 - 2024. All rights reserved.