简体   繁体   English

在 Python 中的列表中存储列表

[英]Storing lists within lists in Python

I have a question about accessing elements in lists.我对访问列表中的元素有疑问。

This is the code:这是代码:

movies = ["The Holy Grail", 1975, "Terry Jones and Terry Gilliam", 91,
          ["Graham Champman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]]

print(movies[4][1][3])

And this is the output: Eric Idle这是 output: Eric Idle

My question is why is the output Eric Idle?我的问题是为什么 output Eric Idle? What does 4 represent, what do 1 and 3 represent? 4代表什么,1和3代表什么? I'm so confused.我很混乱。

Your list is separated into values.您的列表分为值。

# movies: values
0. "The Holy Grail"
1. 1975
2. "Terry Jones and Terry Gilliam"
3. 91
4. ["Graham Champman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]

/!\ The index begin from 0 /!\ 索引从 0 开始

The last value is also separated into values:最后一个值也分为值:

# movies[4]: values
0. "Graham Champman"
1. ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]

And the last value is also separated into other values:最后一个值也被分成其他值:

# movies[4][1]: values
0. "Michael Palin",
1. "John Cleese"
2. "Terry Gilliam"
3. "Eric Idle"
4. "Terry Jones"

So calling movies[4] returns the last element of movies :所以调用movies[4]返回movies的最后一个元素:

["Graham Champman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]

Typing movies[4][1] returns this:输入movies[4][1]会返回:

["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]

And typing movies[4][1][3] returns that:输入movies[4][1][3]会返回:

"Eric Idle"

Tree view树视图

movies
 0. | "The Holy Grail"
 1. | 1975
 2. | "Terry Jones and Terry Gilliam"
 3. | 91
 4. |____
    4.0. | "Graham Champman"
    4.1. |____
        4.1.0 | "Michael Palin"
        4.1.1 | "John Cleese"
        4.1.2 | "Terry Gilliam"
        4.1.3 | "Eric Idle"
        4.1.4 | "Terry Jones"

Hope that helped.希望有帮助。

Please review The Python Tutorial to familiarize yourself with Python basics.请查看Python 教程以熟悉 Python 基础知识。 Lists in Python can be indexed (starting with 0) and accessed using square brackets. Python 中的列表可以被索引(从 0 开始)并使用方括号进行访问。

In your case, sub_ele = movies[4] is accessing the fifth element of the list movies, which is (in this case) a list of length two.在您的情况下, sub_ele = movies[4]正在访问列表电影的第五个元素,即(在这种情况下)长度为 2 的列表。 Hence subsub_ele = sub_ele[1] is accessing the second element of the sub list, which is (in this case) a list of length five.因此subsub_ele = sub_ele[1]正在访问子列表的第二个元素,它(在这种情况下)是一个长度为 5 的列表。 Lastly, subsub_ele[3] is accessing the fourth element of the sub sub list, which is finally "Eric Idle".最后, subsub_ele[3]正在访问子子列表的第四个元素,最后是“Eric Idle”。

Hopefully, it is now clear.希望现在很清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM