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

我的梦境 提交于 2020-01-10 01:15:08

问题


Let's say i have an array of Tuples, s, in the form of:

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 = (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?


回答1:


No.

t = tuple(x[0] for x in s)



回答2:


The list comprehension method given by Ignacio is the cleanest.

Just for kicks, you could also do:

zip(*s)[0]

*s expands s into a list of arguments. So it is equivalent to

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.




回答3:


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.

In Python 2.x, zip returns a tuple. izip uses less memory since iterators do not generate their contents until needed.

In Python 3, zip returns an iterator.



来源:https://stackoverflow.com/questions/2054416/getting-the-first-elements-per-row-in-an-array-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!