[英]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,它来自外部文件(实际上,这是一个很大的列表, len(M)>10000
)。
M=[(1, 100), (2, 200), (3, 300), (4, 400)] 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]
. 但是,我想将其分为M1=[1,2,3,4]
和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. 我想知道是否有一种更简单,更有效的方法来完成此工作,该解决方案使用Python中的内置函数。
Just do it: 去做就对了:
M1, M2 = zip(*M)
M1 and M2 will be tuples. M1和M2将是元组。 You can transform them into lists if you want: 您可以根据需要将它们转换为列表:
M1, M2 = map(list, zip(*M))
or with a genexp: 或使用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
: 但是更好的是使用*
运算符和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. 如果您确实有一个较长的外部文件,则您的初始版本可能会更快,因为此方法将向zip发送10k参数,因此将所有内容保留在内存中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.