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.
Вопрос
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?
Решение
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.
Другие советы
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))
A 2-tuple
is a pair. You can access the first and second elements like this:
x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1
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]
.
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++
pair = Pair
pair.make_pair(value1, value2)
or
pair = Pair(value1, value2)
here's the source code pair_stl_for_python
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