【问题标题】:Python to list all the combinations of any-3-elements in a listPython列出列表中任意3个元素的所有组合
【发布时间】:2022-11-14 03:17:55
【问题描述】:

找到一种方法来列出列表中任意 3 个元素的所有组合:

这是我尝试过的:

import itertools

the_list = ["Alpha","Beta","Gamma","Delta","Epsilon","Zeta"]


list_of_trios = [(the_list[p1], the_list[p2], the_list[p3]) for p1 in range(len(the_list)) for p2 in range(p1+1,len(the_list)) for p3 in range(p1+2,len(the_list))]
tem_list = []


for each in list_of_trios:
    check_me = list(set(each))
    if len(check_me) == 3:
        tem_list.append(check_me)

tem_list.sort()

final_list = list(tem_list for tem_list, _ in itertools.groupby(tem_list))

for ox in final_list:
    print (ox)

它似乎工作。实现这一目标的更好方法是什么?

【问题讨论】:

  • 使用itertools.combinationsitertools.permutations

标签: python list loops combinations


【解决方案1】:

https://docs.python.org/3/library/itertools.html?highlight=comb#itertools.combinations

from itertools import combinations

the_list = ["Alpha","Beta","Gamma","Delta","Epsilon","Zeta"]

list_of_trios = list(combinations(the_list, 3))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多