对于给定列表,获得实际两点组合的最佳解决方案是什么?

2024-10-02 10:21:12 发布

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

我有一个类似这样的列表,我想要两点解的所有组合

list1=['a','b','c','d','e','f','g','h']

我需要这个预期结果中的所有28个组合

[['a','b'],['a','c'],['a','d'],['a','e'],['a','f'],['a','g'],['a','h'],
['b','c'],['b','d'],['b','e'],['b','f'],['b','g'],['b','h'],
['c','d'],['c','e'],['c','f'],['c','g'],['c','h'],
['d','e'],['d','f'],['d','g'],['d','h'],
['e','f'],['e','g'],['e','h'],
['f','g'],['f','h'],
['g','h']]

这个链接解释了28种组合是如何实现的。 https://www.calculatorsoup.com/calculators/discretemathematics/combinations.php

我试过scipy

from scipy.special import comb
comb(8, 2, exact=True)

但它并没有给我实际的组合,而是给了我一些可能的组合

itertools给了我内存错误。在我的df[“ID”]列表中,将有1000多个元素

len(list(combinations(df["ID"].to_list(),5)))

如果我想要三点解,那么可能的组合是56

谢谢你的帮助


Tags: httpscomiddf列表链接wwwscipy
1条回答
网友
1楼 · 发布于 2024-10-02 10:21:12

使用itertools.combinations返回28个组合

itertools.combinations(list1, 2)

#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('a', 'g'), ('a', 'h'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('b', 'g'), ('b', 'h'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('c', 'g'), ('c', 'h'), ('d', 'e'), ('d', 'f'), ('d', 'g'), ('d', 'h'), ('e', 'f'), ('e', 'g'), ('e', 'h'), ('f', 'g'), ('f', 'h'), ('g', 'h')]

len(list(itertools.combinations(list1, 2)))
#28

相关问题 更多 >

    热门问题