How to convert multiple lists to a list using Python?

I want to convert multiple lists inside a list? I do this with a loop, but each subscription item does not get a comma between it.

myList = [['a','b','c','d'],['a','b','c','d']]
myString = ''
for x in myList:
    myString += ",".join(x)
print myString

Ouput:

a,b,c,da,b,c,d

desired result:

a,b,c,d,a,b,c,d
+4
source share
4 answers

This can be done using an understanding of the list, in which you "flatten" the list of lists in one list, and then use the "join" method to make your list a string. The "," parameter indicates the separation of each part of the comma.

','.join([item for sub_list in myList for item in sub_list])

Note. Please review my analysis below for what has been tested to be the fastest solution for others offered here.

Demo:

myList = [['a','b','c','d'],['a','b','c','d']]
result = ','.join([item for sub_list in myList for item in sub_list])

a,b,c,d,a,b,c,d

, , , :

# create a new list called my_new_list
my_new_list = []
# Next we want to iterate over the outer list
for sub_list in myList:
    # Now go over each item of the sublist
    for item in sub_list:
        # append it to our new list
        my_new_list.append(item)

, my_new_list :

['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']

, , , . ','.join(). :

myString = ','.join(my_new_list)

, :

a,b,c,d,a,b,c,d

, , . , , , . !

, , . :

  • : 3.8023074030061252
  • : 7.675725881999824
  • : 8.73164687899407

, . - , , :

from timeit import Timer


def comprehension(l):
    return ','.join([i for sub_list in l for i in sub_list])


def chain(l):
    from itertools import chain
    return ','.join(chain.from_iterable(l))


def a_map(l):
    return ','.join(map(','.join, l))

myList = [[str(i) for i in range(10)] for j in range(10)]

print(Timer(lambda: comprehension(myList)).timeit())
print(Timer(lambda: chain(myList)).timeit())
print(Timer(lambda: a_map(myList)).timeit())
+7
from itertools import chain

myList = [['a','b','c','d'],['a','b','c','d']]

print(','.join(chain.from_iterable(myList)))

a,b,c,d,a,b,c,d
+7

You can also just join both levels:

>>> ','.join(map(','.join, myList))
'a,b,c,d,a,b,c,d'

It is shorter and significantly faster than other solutions:

>>> myList = [['a'] * 1000] * 1000
>>> from timeit import timeit

>>> timeit(lambda: ','.join(map(','.join, myList)), number=10)
0.18380278121490046

>>> from itertools import chain
>>> timeit(lambda: ','.join(chain.from_iterable(myList)), number=10)
0.6535200733309843

>>> timeit(lambda: ','.join([item for sub_list in myList for item in sub_list]), number=10)
1.0301431917067738

I also tried [['a'] * 10] * 10, [['a'] * 10] * 100000and [['a'] * 100000] * 10, and it was always the same picture.

+1
source
myList = [['a','b','c','d'],[a','b','c','d']]
smyList = myList[0] + myList[1]
str1 = ','.join(str(x) for x in smyList)
print str1

output

a,b,c,d,a,b,c,d
0
source

Source: https://habr.com/ru/post/1612323/


All Articles