Python 如何访问配对列表中配对的每个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22496657/
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
How can I access each element of a pair in a pair list?
提问by impossible
I have a list called pairs.
我有一个名为pairs的列表。
pairs = [("a", 1), ("b", 2), ("c", 3)]
And I can access elements as:
我可以访问元素为:
for x in pairs:
print x
which gives output like:
这给出了如下输出:
('a', 1) ('b', 2) ('c', 3)
But I want to access each element in each pair, like in c++, if we use pair<string, int>we are able to access, first element and second element by x.first, and x.second.eg.
但是我想访问每一对中的每个元素,就像在 c++ 中一样,如果我们使用pair<string, int>我们可以访问,第一个元素和第二个元素 byx.first和x.second.eg。
x = make_pair("a",1)
x.first= 'a'
x.second= 1
How can I do the same in python?
我如何在 python 中做同样的事情?
采纳答案by alecxe
Use tuple unpacking:
使用元组解包:
>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
... print a, b
...
a 1
b 2
c 3
See also: Tuple unpacking in for loops.
另请参阅:在 for 循环中解包元组。
回答by Jayanth Koushik
A 2-tupleis a pair. You can access the first and second elements like this:
A2-tuple是一对。您可以像这样访问第一个和第二个元素:
x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1
回答by Hugh Bothwell
If you want to use names, try a namedtuple:
如果要使用名称,请尝试命名元组:
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]
for pair in pairs:
print("First = {}, second = {}".format(pair.first, pair.second))
回答by henrebotha
When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0]or [1]after its name. So all you have to do to get the first element of the first element of pairis say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].
当你说pair[0],那给你("a", 1)。括号中的东西是一个元组,它和列表一样,是一种集合。因此,您可以通过指定[0]或[1]在其名称之后访问该事物的第一个元素。所以你需要做的就是获取第一个元素的第一个元素pairsay pair[0][0]。或者如果你想要第三个元素的第二个元素,它是pair[2][1].
回答by Nikunj Parmar
You can access the members by their index in the tuple.
您可以通过元组中的索引访问成员。
lst = [(1,'on'),(2,'onn'),(3,'onnn'),(4,'onnnn'),(5,'onnnnn')]
def unFld(x):
for i in x:
print(i[0],' ',i[1])
print(unFld(lst))
Output :
输出 :
1 on
2 onn
3 onnn
4 onnnn
5 onnnnn
回答by Baraa Al-Masri
I don't think that you'll like it but I made a pair port for python :) using it is some how similar to c++
我不认为你会喜欢它,但我为 python 制作了一对端口 :) 使用它与 c++ 有点相似
pair = Pair
pair.make_pair(value1, value2)
or
或者
pair = Pair(value1, value2)
here's the source code pair_stl_for_python
这是源代码 pair_stl_for_python

