在Python中使用namedtuple访问for循环的索引

0 投票
2 回答
1178 浏览
提问于 2025-04-18 01:03

如果我有一个整数的列表,想要遍历这个列表,获取每个元素和它的索引,我可以这样做:

for idx, val in enumerate(ints):
    print idx, val

那么,如何用一个命名元组的列表来做同样的事情呢?

Point = namedtuple("Point", ['x', 'y'])
#Append points
points.append(p1)
...

#This gives me the x,y coordinates from the points, not the iteration index.
for i,p in points:
    print(str(i) + ' ' + str(p))

2 个回答

2

如果你想在每次循环中获取索引,还是需要使用 enumerate。列表的内容并不会改变标准循环的行为,除了当列表里面包含可迭代的对象时,像 for x, y in points 这样的写法是可以使用的。

for i, p in enumerate(points):
    print(str(i) + ' ' + str(p))

为了后续参考:从 Python 2.7 开始,你可以像这样嵌套你的元组解包:

for i, (x, y) in enumerate(points):
    print('%d (%s, %s)'.format(i, x, y))
3

试试这个:

for i, p in enumerate(points):
    print(str(i) + ' ' + str(p))

enumerate() 这个函数会自动给你传入的任何可迭代对象(比如列表、元组等)加上索引,也就是位置编号。

撰写回答