Python 访问列表中元组中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4800811/
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
Accessing a value in a tuple that is in a list
提问by super9
[(1,2), (2,3), (4,5), (3,4), (6,7), (6,7), (3,8)]
How do I return the 2nd value from each tuple inside this list?
如何从此列表中的每个元组返回第二个值?
Desired output:
期望的输出:
[2, 3, 5, 4, 7, 7, 8]
采纳答案by Ignacio Vazquez-Abrams
回答by gary
Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in DiveIntoPython3, for example). Here are a few points:
Ignacio 的答案正是您想要的。然而,作为一个也在学习 Python 的人,让我试着为你剖析它......如前所述,它是一个列表理解(例如在DiveIntoPython3 中介绍)。这里有几点:
[x[1] for x in L]
[x[1] for x in L]
- Notice the
[]'s around the line of code. These are what define a list. This tells you that this code returns a list, so it's of thelisttype. Hence, this technique is called a "list comprehension." - L is your original list. So you should define
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]prior to executing the above code. xis a variable that only exists in the comprehension - try to accessxoutside of the comprehension, or typetype(x)after executing the above line and it will tell youNameError: name 'x' is not defined, whereastype(L)returns<class 'list'>.x[1]points to the seconditem in each of the tuples whereasx[0]would point to each of the first items.- So this line of code literally reads "return the second item in a tuple for all tuples in list L."
- 请注意
[]代码行周围的 。这些是定义列表的内容。这告诉您此代码返回一个列表,因此它属于该list类型。因此,这种技术被称为“列表理解”。 - L 是您的原始列表。所以你应该
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]在执行上面的代码之前定义。 x是一个仅存在于推导中的变量 - 尝试在推导x之外访问,或type(x)在执行上述行后键入,它会告诉您NameError: name 'x' is not defined,而type(L)返回<class 'list'>.x[1]指向每个元组中的第二个项目,而x[0]将指向每个第一个项目。- 所以这行代码字面意思是“为列表 L 中的所有元组返回元组中的第二项”。
It's tough to tell how much you attempted the problem prior to asking the question, but perhaps you just weren't familiar with comprehensions? I would spend some time reading through Chapter 3 of DiveIntoPython, or any resource on comprehensions. Good luck.
在提出问题之前很难判断您尝试了多少问题,但也许您只是不熟悉理解?我会花一些时间阅读DiveIntoPython 的第 3 章,或任何有关理解的资源。祝你好运。
回答by aaronasterling
A list comprehension is absolutely the way to do this. Another way that shouldbe faster is mapand itemgetter.
列表理解绝对是做到这一点的方法。另一种应该更快的方法是mapand itemgetter。
import operator
new_list = map(operator.itemgetter(1), old_list)
In response to the comment that the OP couldn't find an answer on google, I'll point out a super naive way to do it.
针对 OP 无法在 google 上找到答案的评论,我将指出一种非常幼稚的方法。
new_list = []
for item in old_list:
new_list.append(item[1])
This uses:
这使用:
- Declaring a variable to reference an empty list.
- A for loop.
- Calling the
appendmethod on a list.
- 声明一个变量来引用一个空列表。
- 一个 for 循环。
- 调用
append列表上的方法。
If somebody is trying to learn a language and can't put together these basic pieces for themselves, then they need to view it as an exerciseand do it themselves even if it takes twenty hours.
如果有人正在尝试学习一门语言并且无法为自己整理这些基本部分,那么他们需要将其视为练习并自己做,即使需要二十个小时。
One needs to learn how to think about what one wantsand compare that to the available tools. Every element in my second answer should be covered in a basic tutorial. You cannot learn to program without reading one.
人们需要学习如何思考自己想要什么,并将其与可用工具进行比较。我的第二个答案中的每个元素都应该包含在基本教程中。不阅读一本就无法学习编程。
回答by jpp
You can also use sequence unpacking with zip:
您还可以使用序列解包zip:
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
_, res = zip(*L)
print(res)
# (2, 3, 5, 4, 7, 7, 8)
This also creates a tuple _from the discarded first elements. Extracting only the second is possible, but more verbose:
这也会_从丢弃的第一个元素创建一个元组。仅提取第二个是可能的,但更详细:
from itertools import islice
res = next(islice(zip(*L), 1, None))
回答by U10-Forward
OR you can use pandas:
或者你可以使用pandas:
>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0 2
1 3
2 5
3 4
4 7
5 7
6 8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
Or numpy:
或者numpy:
>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>

