Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two lists to string [duplicate]

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.

like image 822
chill0r Avatar asked Mar 29 '13 12:03

chill0r


3 Answers

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
like image 186
arshajii Avatar answered Oct 04 '22 03:10

arshajii


>>> 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()

  • Eventually ''.join(...) merges the list items into a single string with no separator.
like image 24
ThiefMaster Avatar answered Oct 04 '22 03:10

ThiefMaster


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().

like image 38
Ashwini Chaudhary Avatar answered Oct 04 '22 02:10

Ashwini Chaudhary