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
, , , :
my_new_list = []
for sub_list in myList:
for item in sub_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())