Actually I'm trying to merge two lists to one string but keep them ordered meaning:
list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]
result = "1one2two3three4four5five"
(lists always have the same length but vary in contents)
At the moment I'm doing it this way:
result = ""
i = 0
for entry in list1:
result += entry + list2[i]
i += 1
I think there must be a more pythonic way to do this but I don't know it actually.
May someone of you can help me out on this.
list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]
print ''.join([str(a) + b for a,b in zip(list1,list2)])
1one2two3three4four5five
>>> import itertools
>>> ''.join(map(str, itertools.chain.from_iterable(zip(list1, list2))))
1one2two3three4four5five'
Explanation:
zip(list1, list2) creates a list containing tuples of matching elements from the two lists:
>>> zip(list1, list2)
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]
itertools.chain.from_iterable() flattens that nested list:
>>> list(chain.from_iterable(zip(list1, list2)))
[1, 'one', 2, 'two', 3, 'three', 4, 'four', 5, 'five']
Now we need to ensure that there are only strings, so we apply str() to all items using map()
''.join(...) merges the list items into a single string with no separator.Using string formatting with str.join() and zip():
>>> list1 = [1,2,3,4,5]
>>> list2 = ["one", "two", "three", "four", "five"]
>>> "".join("{0}{1}".format(x,y) for x,y in zip(list1,list2))
'1one2two3three4four5five'
zip(list1,list2) returns something like this:
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')].
Now for each item of this list we apply the string formatting and then join the whole generator expression using str.join().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With