+ 2

trying to make list permutation in python

I need to make a list of all permutations, but the catch is every element comes from a different list. It is supposed to be for a random number of lists. for example list1=[1,2,3,4] list2=[a,b,c,d] list3=[...] ... the result should be something like this: [1,a...],[1,b...],[1,c...]..,[2,a..],[2,b]....[4,d..]..

9th Apr 2022, 7:23 AM
Mihail
Mihail - avatar
4 Réponses
+ 5
Mihail , this does currently not cover your request for a random number of list, but i try to come back later: from itertools import product # generates the cartesian products of n iterables list1 = [1,2,3,4] list2 = ["a","b","c","d"] print(list(product(list1, list2))) [EDITED]: i have done a try, you can find it in the file. there are also some comments included. it may not be perfect for your purpose, but you can see how it can be done: https://code.sololearn.com/c7ZBA00EOhT5/?ref=app
9th Apr 2022, 10:49 AM
Lothar
Lothar - avatar
+ 4
Using nested list comprehension list1 = [1,2,3,4] list2 = ["a","b","c","d"] list3 = [[i,j] for i in list1 for j in list2] print(list3)
9th Apr 2022, 9:04 AM
Simba
Simba - avatar
+ 1
but i don't know the number of lists beforehand
9th Apr 2022, 9:53 AM
Mihail
Mihail - avatar
+ 1
Lothar is right for as long as there is required a random number of lists. This comes from the fact that product() xan accept a arbitrary number of lists, so this must be true. In fact, there can be chosen a random number (i) bellow or equal to a certain number of lists in ready for use and then picking randomly lists for (i) times and then applying product()
9th Apr 2022, 12:08 PM
Ervis Meta
Ervis Meta - avatar