简体   繁体   English

Python 列出列表中任意 3 个元素的所有组合

[英]Python to list all the combinations of any-3-elements in a list

Finding a way to list all the combinations of any-3-elements in a list:找到一种方法来列出列表中任意 3 个元素的所有组合:

Here is what I tried:这是我尝试过的:

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)

It seems to work.它似乎工作。 What would be the better way to achieve this?实现这一目标的更好方法是什么?

https://docs.python.org/3/library/itertools.html?highlight=comb#itertools.combinations 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM