Python 如何从元组列表中提取第 n 个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3308102/
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 10:23:31  来源:igfitidea点击:

How to extract the n-th elements from a list of tuples?

pythonlisttuples

提问by pleasedontbelong

I'm trying to obtain the n-th elements from a list of tuples.

我试图从元组列表中获取第 n 个元素。

I have something like:

我有类似的东西:

elements = [(1,1,1),(2,3,7),(3,5,10)]

I wish to extract only the second elements of each tuple into a list:

我希望只将每个元组的第二个元素提取到一个列表中:

seconds = [1, 3, 5]

I know that it could be done with a forloop but I wanted to know if there's another way since I have thousands of tuples.

我知道它可以用for循环来完成,但我想知道是否有另一种方法,因为我有数千个元组。

采纳答案by luc

n = 1 # N. . .
[x[n] for x in elements]

回答by Mark Byers

I know that it could be done with a FOR but I wanted to know if there's another way

我知道可以用 FOR 来完成,但我想知道是否还有其他方法

There is another way. You can also do it with mapand itemgetter:

还有另一种方法。你也可以用mapitemgetter来做到:

>>> from operator import itemgetter
>>> map(itemgetter(1), elements)

This still performs a loop internally though and it is slightly slower than the list comprehension:

虽然这仍然在内部执行循环,但它比列表理解略慢:

setup = 'elements = [(1,1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))

Results:

结果:

Method 1: 1.25699996948
Method 2: 1.46600008011

If you need to iterate over a list then using a foris fine.

如果您需要遍历列表,那么使用 afor就可以了。

回答by Daren Thomas

This also works:

这也有效:

zip(*elements)[1]

(I am mainly posting this, to prove to myself that I have groked zip...)

(我主要是发这个,向自己证明我已经摸透了zip......)

See it in action:

看看它在行动:

>>> help(zip)

Help on built-in function zip in module builtin:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

模块builtin 中内置函数 zip 的帮助:

压缩(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

返回元组列表,其中每个元组包含每个参数序列中的第 i 个元素。返回的列表在长度上被截断为最短参数序列的长度。

>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> zip(*elements)
[(1, 2, 3), (1, 3, 5), (1, 7, 10)]
>>> zip(*elements)[1]
(1, 3, 5)
>>>

Neat thing I learned today: Use *listin arguments to create a parameter list for a function...

我今天学到的一件事:*list在参数中使用为函数创建参数列表......

Note: In Python3, zipreturns an iterator, so instead use list(zip(*elements))to return a list of tuples.

注意:在 Python3 中,zip返回一个迭代器,所以用它list(zip(*elements))来返回一个元组列表。

回答by Graeme Gellatly

Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method

发现这个是因为我正在寻找哪种方式可以最快地拉出 2 元组列表的第二个元素。不是我想要的,而是使用第三种方法进行了相同的测试,并测试了 zip 方法

setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))

Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499

So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.

所以如果你有一个 2 元组对来转换为一个 dict 并取值,那么速度会快两倍。

回答by Thras

map (lambda x:(x[1]),elements)

回答by Oleg

Timings for Python 3.6for extracting the second element from a 2-tuple list.

定时为Python的3.6,用于从2元组列表中提取第二元件。

Also, added numpyarray method, which is simpler to read (but arguably simpler than the list comprehension).

此外,添加了numpy数组方法,它更易于阅读(但可以说比列表理解更简单)。

from operator import itemgetter
elements = [(1,1) for _ in range(100000)]

%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]

and the timings:

和时间:

list comprehension:  4.73 ms ± 206 μs per loop
list(map):           5.3 ms ± 167 μs per loop
dict:                2.25 ms ± 103 μs per loop
list(zip)            5.2 ms ± 252 μs per loop
numpy array:        28.7 ms ± 1.88 ms per loop

Note that map()and zip()do not return a list anymore, hence the explicit conversion.

请注意,map()并且zip()不再返回列表,因此是显式转换。

回答by Georgy

Using isliceand chain.from_iterable:

使用islicechain.from_iterable

>>> from itertools import chain, islice
>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> list(chain.from_iterable(islice(item, 1, 2) for item in elements))
[1, 3, 5]

This can be useful when you need more than one element:

当您需要多个元素时,这会很有用:

>>> elements = [(0, 1, 2, 3, 4, 5), 
                (10, 11, 12, 13, 14, 15), 
                (20, 21, 22, 23, 24, 25)]
>>> list(chain.from_iterable(islice(tuple_, 2, 5) for tuple_ in elements))
[2, 3, 4, 12, 13, 14, 22, 23, 24]