Reputation: 2834
Suppose I have
lists = ["ABC","AC","CCCC","BC"]
I want a new list where items in my new list are grouped by position based on lists
meaning for each string in the list take the position 0("ABC" position 0 is "A") and make a string out of it.
position = ["AACB","BCCC","CC","C"]
I try:
for i in range(0,4):
want = [lists[i] for stuff in lists]
and I get
IndexError: string index out of range
Which makes sense because all the strings are different size. Can anyone help?
Upvotes: 0
Views: 88
Reputation: 11686
You can use this list comprehension:
>>> lists = ["ABC","AC","CCCC","BC"]
>>> [''.join([s[i:i+1] for s in lists]) for i, el in enumerate(lists)]
['AACB', 'BCCC', 'CC', 'C']
Using the slice notation prevents index errors on non-existing elements.
Upvotes: 2
Reputation: 42758
I think you might want this:
import itertools
lists = ["ABC","AC","CCCC","BC"]
position = map(''.join,itertools.izip_longest(*lists, fillvalue=''))
and you get:
['AACB', 'BCCC', 'CC', 'C']
edit: now with the new example...
Upvotes: 5