All possible combinations for 3 digits of list never the same

前端 未结 3 671
温柔的废话
温柔的废话 2021-01-17 01:57

I have a list that looks like:

A
B
C
D
E
F
G

How do I solve this to find all combinations for 3 digits. The same letter cannot be used in

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 02:10

    The Python Standard Library itertools already has the functionality you are trying to implement. Also you are using it in your code (funnily).

    itertools.combinations(a,3) returns all 3-combinations of the a. To convert that to "list of list" you should use .extend() as follows;

    x = ['a','b','c','d','e']
    n = 3
    import itertools
    permutations = []
    combinations = []
    combinations.extend(itertools.combinations(x,n))
    permutations.extend(itertools.permutations(x,n))
    
    print("Permutations;", permutations)
    print("\n")
    print("Combinations;", combinations)
    

    Additionally, I suggest you to search on "Combination, Permutation Difference". As I understood from your question; permutation is what you want. (If you run the code I shared, you will understand the difference easliy.)

提交回复
热议问题