简体   繁体   中英

Separate lists of format M=[(a,x), (b,y)] into M1=[a,b] and M2=[x,y]

I have a list M below which came from an external file (This is a large list in reality, len(M)>10000 ).

M=[(1, 100), (2, 200), (3, 300), (4, 400)]

However, I want to separate it into M1=[1,2,3,4] and M2=[100,200,300,400] . Here is how I do it at the moment,

 M1 = [] M2 = [] for M1,M2 in M: M1.append(M1) M2.append(M2) 

I was wondering if there is a simpler and more efficient way to do it, a solution that uses built-in functions in Python.

Just do it:

M1, M2 = zip(*M)

M1 and M2 will be tuples. You can transform them into lists if you want:

M1, M2 = map(list, zip(*M))

or with a genexp:

M1, M2 = (list(i) for i in zip(*M))

One solution, more efficient than yours because it uses implicit loops is:

>>> [m1 for m1, _ in M]
>>> [1, 2, 3, 4]
>>> [m2 for _, m2 in M]
>>> [100, 200, 300, 400]

But better is using the * operator and zip :

>>> M1, M2 = zip(*M)
>>> M1
(1, 2, 3, 4)
>>> M2
(100, 200, 300, 400)

You could do

M1, M2 = zip(*M)

That works for tuples as well as lists.

If you really have a long external file though, your initial version might be faster, as this approach will send 10k arguments to zip, and hence keep all the content in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM