Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

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

My question is why is the output Eric Idle? What does 4 represent, what do 1 and 3 represent? I'm so confused.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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:

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

Typing movies[4][1] returns this:

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

And typing movies[4][1][3] returns that:

"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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...