如何创建其中包含列表的列表的所有可能组合?

How to create all possible combinations of a list which has lists inside of it?

我有一个看起来像这样的列表

[['Macau', 'United Kingdom', 'India'],
 ['United States', 'China'],
 ['China', 'Australia']]

我想要这些国家/地区的所有可能组合,但组合需要限制在小列表中,我不希望它们混在一起。

例如我想要

[('Macau', 'India'), ('United Kingdom', 'India'), ('Macau', 'United Kingdom'), ('United States', 'China')...]

可能的解决方案如下:

from itertools import combinations

lst = [['Macau', 'United Kingdom', 'India'], ['United States', 'China'],  ['China', 'Australia']]

print([list(combinations(group, 2)) for group in lst])

Returns

[[('Macau', 'United Kingdom'),
  ('Macau', 'India'),
  ('United Kingdom', 'India')],
 [('United States', 'China')],
 [('China', 'Australia')]]

使用 set 和 itertools 按分组查找所有可能的组合

import itertools

data=[['Macau', 'United Kingdom', 'India'],
 ['United States', 'China'],
 ['China', 'Australia']]

lst=[]
for item in data:
    result=list(itertools.combinations(set(item), 2))
    lst.append(result)
    #print(result)
    
print(lst)

输出:

[[('United Kingdom', 'Macau'), ('United Kingdom', 'India'), ('Macau', 'India')], [('United States', 'China')], [('Australia', 'China')]]