Reference an Element in a List of Tuples

后端 未结 7 415
无人共我
无人共我 2020-12-08 10:37

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 w

7条回答
  •  执笔经年
    2020-12-08 11:13

    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
    

提交回复
热议问题