I have a list, to make it easier to understand it's structure I'll write it out like so:
mylist = [[["a","b","c","d"]...]...]
Where the ...
means the previous list is repeated (although the values inside may change)
An example list would be:
mylist = [[["a","b","c","d"], ["e","f","g","h"]], [["i", "j", "k", "l"]], [["m","n","o","p"], ["q","r","s","t"]]]
My current method is:
mylist2 = []
for a in mylist[0]:
for b in mylist[1]:
for c in mylist[2]:
mylist2.append([a,b,c])
However this is very long, especially since in my actual code it goes on up to for x in mylist[35]
Is there a better way for me to write this code?
your code
%%timeit
mylist2 = []
for a in mylist[0]:
for b in mylist[1]:
for c in mylist[2]:
mylist2.append([a,b,c])
# 809 ns ± 18.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
use itertools
import itertools
%%timeit
list(itertools.product(*mylist))
# 528 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.