How to merge an arbitrary number of tuples in Python?

I have a list of tuples:

l=[(1,2,3),(4,5,6)] 

The list can be of arbitrary length, like tuples. I would like to convert this to a list or tuple of elements in the order in which they appear:

 f=[1,2,3,4,5,6] # or (1,2,3,4,5,6) 

If during development I know how many tuples I will return, I would simply add them:

 m = l[0] + l[1] # (1,2,3,4,5,6) 

But since I do not know until the runtime succeeds, I cannot do this. I feel that there is a way to use map for this, but I cannot figure it out. I can iterate over tuples and add them to the drive, but this will create many intermediate tuples that will never be used. I could also iterate over the tuples, then the elements of the tuples and add them to the list. It seems very inefficient. Maybe there is an even simpler way that I am completely silent. Any thoughts?

+6
source share
7 answers

Chain (creates a generator instead of reserving additional memory):

 >>> from itertools import chain >>> l = [(1,2,3),(4,5,6)] >>> list(chain.from_iterable(l)) [1, 2, 3, 4, 5, 6] 
+15
source
 l = [(1, 2), (3, 4), (5, 6)] print sum(l, ()) # (1, 2, 3, 4, 5, 6) 
+9
source
 reduce(tuple.__add__, [(1,2,3),(4,5,6)]) 
+2
source
 tuple(i for x in l for i in x) # (1, 2, 3, 4, 5, 6) 
+2
source

Use the python generator style for all of the following:

 b=[(1,2,3),(4,5,6)] list = [ x for x in i for i in b ] #produces a list gen = ( x for x in i for i in b ) #produces a generator tup = tuple( x for x in i for i in b ) #produces a tuple print list >> [1, 2, 3, 4, 5, 6] 
+2
source
 >>> from itertools import chain >>> l = [(1,2,3),(4,5,6)] >>> list(chain(*l)) [1, 2, 3, 4, 5, 6] 
+1
source

You can combine the values ​​in the list with the .extend() function as follows:

 l = [(1,2,3), (4,5,6)] m = [] for t in l: m.extend(t) 

or shorter version using the abbreviation:

 l = [(1,2,3), (4,5,6)] m = reduce(lambda x,y: x+list(y), l, []) 
0
source

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


All Articles