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

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

问题描述

抱歉,我是 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天全站免登陆