-1

I have 4 lists, i want them to be like the result

['a', 'b', 'c', 'd']
['e', 'f', 'g']
['h', 'i']
['j', 'k', 'l', 'm', 'n']

result --> ['aehj'], ['bfik'], ['cgl'], ['dm'], ['n']
yehezkel horoviz
  • 198
  • 3
  • 10

2 Answers2

7

You can use itertools.zip_longest with a fill value of '' like so

from itertools import zip_longest

a = ['a', 'b', 'c', 'd']
b = ['e', 'f', 'g']
c = ['h', 'i']
d = ['j', 'k', 'l', 'm', 'n']


result = [[''.join(i)] for i in zip_longest(a, b, c, d, fillvalue='')]
print(result)

will give

[['aehj'], ['bfik'], ['cgl'], ['dm'], ['n']]
tomjn
  • 5,100
  • 1
  • 9
  • 24
0

In pure python

lists = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g'],
  ['h', 'i'],
  ['j', 'k', 'l', 'm', 'n'],
]
results = []
for i in range(0, max(map(len, lists))):
    result = list(map(lambda list: list[i] if i < len(list) else "", lists))
    results.append( "".join(result) )

print(results)
['aehj', 'bfik', 'cgl', 'dm', 'n']
James McGuigan
  • 7,542
  • 4
  • 26
  • 29