使用itertools无法获得正确的组合

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

我正在尝试使用itertools来获得组合,但我没有以我想要的格式获得组合。

import itertools

dict = {(1,):1, (2,):3, (3,):1}
combo = list(itertools.combinations(dict.keys(),2))
print(combo)

输出:

[(('1',), ('2',)), (('1',), ('3',)), (('2',), ('3',))]

我想要的输出:

[('1','2',), ('1','3',),('2','3',)]
python-3.x dictionary itertools
1个回答
0
投票

预期输出,因为您的字典键是元组。您可以尝试以下操作:

>>> combo = list(itertools.combinations((key[0] for key in dict.keys()), 2))
>>> print(combo)
[(1, 2), (1, 3), (2, 3)]

这将从每个字典键中提取第一个([0])元素。

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