在 Python 中获取数组中每行的第一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2054416/
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
Getting the first elements per row in an array in Python?
提问by c00kiemonster
Let's say i have an array of Tuples, s, in the form of:
假设我有一个元组数组,s,形式如下:
s = ((1, 23, 34),(2, 34, 44), (3, 444, 234))
and i want to return another Tuple, t, consisting of the first element per row:
我想返回另一个元组 t,由每行的第一个元素组成:
t = (1, 2, 3)
Which would be the most efficient method to do this? I could of course just iterate through s, but is there any slicker way of doing it?
哪种方法最有效?我当然可以遍历 s,但是有没有更巧妙的方法呢?
回答by Ignacio Vazquez-Abrams
No.
不。
t = tuple(x[0] for x in s)
回答by HS.
The list comprehension method given by Ignacio is the cleanest.
Ignacio 给出的列表理解方法是最干净的。
Just for kicks, you could also do:
只是为了踢,你也可以这样做:
zip(*s)[0]
*s
expands s
into a list of arguments. So it is equivalent to
*s
扩展s
为参数列表。所以它等价于
zip( (1, 23, 34),(2, 34, 44), (3, 444, 234))
And zip
returns n
tuples where each tuple contains the nth
item from each list.
并zip
返回 n
元组,其中每个元组包含nth
每个列表中的项目。
回答by unutbu
import itertools
s = ((1, 23, 34),(2, 34, 44), (3, 444, 234))
print(next(itertools.izip(*s)))
itertools.izip
returns an iterator. The next
function returns the next (and in this case, first) element from the iterator.
itertools.izip
返回一个迭代器。该next
函数从迭代器返回下一个(在本例中为第一个)元素。
In Python 2.x, zip
returns a tuple.
izip
uses less memory since iterators do not generate their contents until needed.
在 Python 2.x 中,zip
返回一个元组。
izip
使用较少的内存,因为迭代器直到需要时才生成它们的内容。
In Python 3, zip
returns an iterator.
在 Python 3 中,zip
返回一个迭代器。