【问题标题】:Cartesian product of a list of tuples元组列表的笛卡尔积
【发布时间】:2021-10-22 06:59:20
【问题描述】:

我会生成一个元组列表的笛卡尔积。

我从一个文本文件开始,其数据如下所示:

1 1
0 1
2 2
3 3
0 5
3 4
5 6
0 -3
-2 -2

然后我得到一个点,我有一个元组列表并且值是整数(从字符串转换):

from csv import reader

f = reader(open('e:\\ucsd\\big_data_analytics\\programs\\week_1\\pa1\\data.txt', 'r'))
flat_list = [item for sublist in list(f) for item in sublist]
res = [tuple(map(int, sub.split(" "))) for sub in flat_list]
print(res)  # [(1, 1), (0, 1), (2, 2), (3, 3), (0, 5), (3, 4), (5, 6), (0, -3), (-2, -2)]

此时,我将求“res”中元组的笛卡尔积。

我是这样使用笛卡尔积的:

colors = ['black', 'white']
sizes = ['S', 'M', 'L']
shirts = [(color, size) for color in colors for size in sizes]
print(shirts)

我不确定如何获得上述元组列表的笛卡尔积。

这是让我难过的格式。

【问题讨论】:

标签: python-3.x cartesian-product


【解决方案1】:

这成功了:

result = [(x, y) for x in res for y in res]

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 2012-05-31
    • 2017-07-15
    • 2012-01-03
    • 2011-07-10
    • 2015-12-05
    • 1970-01-01
    • 2013-07-14
    • 2021-08-25
    相关资源
    最近更新 更多