How can I access each element of a pair in a pair list?

ぃ、小莉子 提交于 2019-12-04 15:31:20

问题


I have a list called 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.

x = make_pair("a",1)
x.first= 'a'
x.second= 1

How can I do the same in python?


回答1:


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.




回答2:


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))



回答3:


A 2-tuple is a pair. You can access the first and second elements like this:

x = tuple('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1



回答4:


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 pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].




回答5:


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


来源:https://stackoverflow.com/questions/22496657/how-can-i-access-each-element-of-a-pair-in-a-pair-list

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