1

I have a list where each element is a long string of characters with same length:

['KLGNVAGELQPFAPSED', 'MPDNVSFELQPPASJED', 'YYLNVSFEDQPPAPMED']

What I want to do is produce a new list, where each element is a string of characters in from same position of first list. You can also imagine same first list as this:

KLGNVAGELQPFAPSED
MPDNVSFELQPPASJED
YYLNVSFEDQPPAPMED

so I want new list to have elements from corresponding columns in first list, like this:

['KMY', 'LPY', 'GDL' 'NNN', ...]

What I tried is this:

for i in sub1:
   for j in i:
      pos.append(j)
   pos.append('\n')

But then I can't manage to separate everything into separate lines.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
estranged
  • 424
  • 5
  • 16

2 Answers2

4

You need to zip the elements of the list together and then join the tuples as strings:

new_list = [''.join(i) for i in zip(*old_list)] # KMY, LPY, GDL, ...
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
3

You can use map and zip

>>> l = ['KLGNVAGELQPFAPSED', 'MPDNVSFELQPPASJED', 'YYLNVSFEDQPPAPMED']
>>> map(''.join,zip(*l))
['KMY', 'LPY', 'GDL', 'NNN', 'VVV', 'ASS', 'GFF', 'EEE', 'LLD', 'QQQ', 'PPP', 'FPP', 'AAA', 'PSP', 'SJM', 'EEE', 'DDD']

Do note that map is faster than a list-comp wherever there is no need of an lambda function.

$ python -m timeit "[''.join(i) for i in zip(*['KLGNVAGELQPFAPSED', 'MPDNVSFELQPPASJED', 'YYLNVSFEDQPPAPMED'])]"
100000 loops, best of 3: 3.54 usec per loop
$ python -m timeit "map(''.join,zip(*['KLGNVAGELQPFAPSED', 'MPDNVSFELQPPASJED', 'YYLNVSFEDQPPAPMED']))"
100000 loops, best of 3: 2.87 usec per loop

You can check out more about the speed difference here

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140