本文介绍了有效地拆分元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有两个元素元组的大列表。我想要两个单独的

列表:一个列表包含每个元组的第一个元素,

第二个列表包含每个元组的第二个元素。


每个元组都包含一个datetime对象,后跟一个整数。


这是原始列​​表的一小部分样本:


((datetime.datetime(2005,7,13,16,0,54),315),

(datetime.datetime(2005,7,13,16,6,12),313 ),

(datetime.datetime(2005,7,13,16,16,45),312),

(datetime.datetime(2005,7,13, 16,22),315),

(datetime.datetime(2005,7,13,16,27,18),312),

(datetime.datetime( 2005,7,13,16,32,35),307),

(datetime.datetime(2005,7,13,16,37,51),304),

(datetime.datetime(2005,7,13,16,43,8),307))


我知道我可以使用''for''循环并创建两个新列表

使用''newList1.append(x)''等。是否有一种有效的方式

来创建这两个新列表s没有使用缓慢的for循环?

$ div $


I have a large list of two element tuples. I want two separate
lists: One list with the first element of every tuple, and the
second list with the second element of every tuple.

Each tuple contains a datetime object followed by an integer.

Here is a small sample of the original list:

((datetime.datetime(2005, 7, 13, 16, 0, 54), 315),
(datetime.datetime(2005, 7, 13, 16, 6, 12), 313),
(datetime.datetime(2005, 7, 13, 16, 16, 45), 312),
(datetime.datetime(2005, 7, 13, 16, 22), 315),
(datetime.datetime(2005, 7, 13, 16, 27, 18), 312),
(datetime.datetime(2005, 7, 13, 16, 32, 35), 307),
(datetime.datetime(2005, 7, 13, 16, 37, 51), 304),
(datetime.datetime(2005, 7, 13, 16, 43, 8), 307))

I know I can use a ''for'' loop and create two new lists
using ''newList1.append(x)'', etc. Is there an efficient way
to create these two new lists without using a slow for loop?

r


推荐答案




不是。你可以通过列表理解获得一点点可爱性

来保持代码简洁,但基本过程将是关于

相同:


a =((1,2),(3,4),(5,6),(7,8),(9,10))

x,y = [[z [ i] for for a in for for in in(0,1)]

#x现在是(1,3,5,7,9),y是(2,4,6,8) ,10)



Not really. You could get a little cutesey with list comprehensions
to keep the code concise, but the underlying process would be about
the same:

a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10))
x,y = [[z[i] for z in a] for i in (0,1)]
# x is now (1,3,5,7,9) and y is (2,4,6,8,10)





Paul的例子的变体:


a =((1,2),(3,4),(5,6),(7,8),(9 ,10))

zip(* a)




[list(t)for t in zip(* a )]如果你需要列表而不是元组。


(我相信这是Guido认为的滥用* args,但是我

只是考虑到优雅使用zip()考虑语言

如何定义* args.YMMV]


-Peter



Variant of Paul''s example:

a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10))
zip(*a)

or
[list(t) for t in zip(*a)] if you need lists instead of tuples.

(I believe this is something Guido considers an "abuse of *args", but I
just consider it an elegant use of zip() considering how the language
defines *args. YMMV]

-Peter




滥用?!这是最有用的之一与它有关。这是

转置。


An abuse?! That''s one of the most useful things to do with it. It''s
transpose.


这篇关于有效地拆分元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:42