Python 使用列表理解构建元组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15410119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:02:46  来源:igfitidea点击:

Use list comprehension to build a tuple

python

提问by Lim H.

How can I use list comprehension to build a tuple of 2-tuple from a list. It would be equivalent to

如何使用列表理解从列表中构建 2 元组的元组。这将相当于

tup = ()
for element in alist:
    tup = tup + ((element.foo, element.bar),)

采纳答案by Pavel Anossov

tup = tuple((element.foo, element.bar) for element in alist)

Technically, it's a generator expression. It's like a list comprehension, but it's evaluated lazily and won't need to allocate memory for an intermediate list.

从技术上讲,它是一个生成器表达式。它就像一个列表推导式,但它是惰性求值的,不需要为中间列表分配内存。

For completeness, the list comprehension would look like this:

为了完整起见,列表推导式如下所示:

tup = tuple([(element.foo, element.bar) for element in alist])

 

 

PS: attrgetteris not faster (alisthas a million items here):

PS:attrgetter不是更快(alist这里有一百万个项目):

In [37]: %timeit tuple([(element.foo, element.bar) for element in alist])
1 loops, best of 3: 165 ms per loop

In [38]: %timeit tuple((element.foo, element.bar) for element in alist)
10 loops, best of 3: 155 ms per loop

In [39]: %timeit tuple(map(operator.attrgetter('foo','bar'), alist))
1 loops, best of 3: 283 ms per loop

In [40]: getter = operator.attrgetter('foo','bar')

In [41]: %timeit tuple(map(getter, alist))
1 loops, best of 3: 284 ms per loop

In [46]: %timeit tuple(imap(getter, alist))
1 loops, best of 3: 264 ms per loop