Skip to content Skip to sidebar Skip to footer

I Want To All List Element Stacked

Is there any way to stack list lis = [['a','b'], ['1', '2', '3'], ['r', 's', 't','u']] i hope return ['a1r','a1s','a1t','a1u','a2r','a2s','a2t','a2u','a3r','a3s','

Solution 1:

The following will do what you want:

import itertools

lis = [['a','b'],
       ['1', '2', '3'],
       ['r', 's', 't','u']]

r = ["".join(t) for t in itertools.product(*lis)]

This will set r to:

['a1r', 'a1s', 'a1t', 'a1u', 'a2r', 'a2s', 'a2t', 'a2u', 'a3r', 'a3s', 'a3t', 'a3u', 'b1r', 'b1s', 'b1t', 'b1u', 'b2r', 'b2s', 'b2t', 'b2u', 'b3r', 'b3s', 'b3t', 'b3u']

Solution 2:

You could achieve that using itertools

from itertools import product
lis = [['a','b'],
        ['1', '2', '3'],
        ['r', 's', 't','u']]

l = list(product(*lis))
l = [''.join(x) for x in l]

Output:

['a1r', 'a1s', 'a1t', 'a1u', 'a2r', 'a2s', 'a2t', 'a2u', 'a3r', 'a3s', 'a3t', 'a3u', 'b1r', 'b1s', 'b1t', 'b1u', 'b2r', 'b2s', 'b2t', 'b2u', 'b3r', 'b3s', 'b3t', 'b3u'] 

Post a Comment for "I Want To All List Element Stacked"