在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:39:43  来源:igfitidea点击:

Getting the first elements per row in an array in Python?

pythontuples

提问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]

*sexpands sinto a list of arguments. So it is equivalent to

*s扩展s为参数列表。所以它等价于

zip( (1, 23, 34),(2, 34, 44), (3, 444, 234))

And zipreturns ntuples where each tuple contains the nthitem 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.izipreturns an iterator. The nextfunction returns the next (and in this case, first) element from the iterator.

itertools.izip返回一个迭代器。该next函数从迭代器返回下一个(在本例中为第一个)元素。

In Python 2.x, zipreturns a tuple. izipuses less memory since iterators do not generate their contents until needed.

在 Python 2.x 中,zip返回一个元组。 izip使用较少的内存,因为迭代器直到需要时才生成它们的内容。

In Python 3, zipreturns an iterator.

在 Python 3 中,zip返回一个迭代器。