Home >Backend Development >Python Tutorial >What is the method for total combination of two lists in Python?

What is the method for total combination of two lists in Python?

王林
王林forward
2023-05-05 20:34:121171browse

What is a full combination?

Two tuples (a, b) (c, d), then their combinations are a,c a,d b,c b,d

Method 1

Through itertools Class generation generates a list of lists containing all potential combinations between the two lists

import itertools

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8,9]
print(list(itertools.product(list1, list2)))

Output results:

[(1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9)]

Way 2

Try using the list generator to create an nested Set list:

>>> [[[x,y] for x in list1] for y in list2]
[[[1, 3], [2, 3]], [[1, 4], [2, 4]]]

Or, if you want a one-line list, just remove the brackets:

>>> [[x,y] for x in list1 for y in list2]
[[1, 3], [1, 4], [2, 3], [2, 4]]

Way 3

repeat the first list, permutate the second list and zip They go together

>>> from itertools import permutations, repeat
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b)))
[[(1, 4), (2, 5), (3, 6)],
 [(1, 4), (2, 6), (3, 5)],
 [(1, 5), (2, 4), (3, 6)],
 [(1, 5), (2, 6), (3, 4)],
 [(1, 6), (2, 4), (3, 5)],
 [(1, 6), (2, 5), (3, 4)]]

Edit: As Peter Otten pointed out, internal zip and repeat are redundant.

[list(zip(a, p)) for p in permutations(b)]

The above is the detailed content of What is the method for total combination of two lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete