在元组列表中引用元素 [英] Reference an Element in a List of Tuples

查看:296
本文介绍了在元组列表中引用元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,但是我是Python的新手.我有一个tuples列表,我想知道如何引用列表中每个tuple的第一个元素.我认为这就像

Sorry in advance, but I'm new to Python. I have a list of tuples, and I was wondering how I can reference, say, the first element of each tuple within the list. I would think it's something like

for i in number_of_tuples :
  first_element = myList[i[0]]

你知道吗,[list_element[tuple_element]]?但是,这似乎不是正确的方法.任何帮助将不胜感激.

you know, [list_element[tuple_element]]? However, this doesn't appear to be the right approach. Any help would be greatly appreciated.

谢谢

特纳

推荐答案

此处的所有其他答案都是正确的,但没有解释您尝试的原因是错误的.当您执行myList[i[0]]时,您会告诉Python i是一个元组,并且您想要值或元组i的第一个元素作为myList的索引.

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

在大多数编程语言中,当您需要访问嵌套数据类型(例如数组,列表或元组)时,可以将方括号附加到最里面的项.第一个括号为您提供了元组在列表中的位置.第二个括号为您提供了该项目在元组中的位置.

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.

这是我想到的一个简单的例子:

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6

这篇关于在元组列表中引用元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆