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

王林
Release: 2023-05-05 20:34:12
forward
1079 people have browsed it

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)))
Copy after login

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)]
Copy after login

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]]]
Copy after login

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]]
Copy after login

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)]]
Copy after login

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

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

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!