我有一个像这样的tupples列表:
tupples=[(41, 'Mike'), (29, 'Tom'), (28, 'Sarah'), (22, 'Jane'), (18, 'John']
整数是个人的年龄,字符串是他们的名字。 tupples是故意按个人年龄排序的。
我理解列表索引在这里工作。因此,如果我想访问第一个tupple,那么:
tupples[0]
将访问
(41, 'Mike')
如何访问tupples中的值?
我想通过tupple循环并打印: "他们是" AGE"岁,他们的名字是"名称。
因此对于tupples [0],它看起来像:
"They are" 41 "years old, and their name is" Mike.
答案 0 :(得分:2)
您可以使用sequence unpacking之类的:
data = [(41, 'Mike'), (29, 'Tom'), (28, 'Sarah'),
(22, 'Jane'), (18, 'John')]
for age, name in data:
print("They are {} years old, and their name is {}.".format(age, name))
或者您可以像[0]
和[1]
一样访问元组中的元素:
for datum in data:
print("They are {} years old, and their name is {}.".format(datum[0], datum[1]))
或者您可以使用argument unpacking之类的:
for datum in data:
print("They are {} years old, and their name is {}.".format(*datum))
答案 1 :(得分:1)
我猜
tupples[1][0]
会工作得很好。
编辑: 如果您希望年龄和姓名都是变量,请执行以下操作:
age, name = tupples[0]