Книга: Practical Programming, Fourth Edition
Назад: List Methods
Дальше: Splitting Strings

Working with a List of Lists

Lists can contain other lists

As stated in , lists can contain items of any data type, including other lists. A list whose items are lists is called a nested list. For example, the following nested list describes life expectancies in different countries:

 >>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]

Here is the memory model that results from the execution of that assignment statement:

Nested lists

Notice that each item in the outer list is itself a list of two items. Use the standard indexing notation to access the items in the outer list:

 >>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]
 >>>​​ ​​life[0]
 ['Canada', 76.5]
 >>>​​ ​​life[1]
 ['United States', 75.5]
 >>>​​ ​​life[2]
 ['Mexico', 72.0]

Since each of these items is also a list, you can index it again, just as you can chain together method calls or nest function calls:

 >>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]
 >>>​​ ​​life[1]
 ['United States', 75.5]
 >>>​​ ​​life[1][0]
 'United States'
 >>>​​ ​​life[1][1]
 75.5

You can also assign inner lists to variables:

 >>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]
 >>>​​ ​​canada​​ ​​=​​ ​​life[0]
 >>>​​ ​​canada
 ['Canada', 76.5]
 >>>​​ ​​canada[0]
 'Canada'
 >>>​​ ​​canada[1]
 76.5

Assigning an inner list to a variable creates an alias for that list:

Sublist

As before, any change you make through the inner list reference will be seen when you access the main list, and vice versa:

 >>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]
 >>>​​ ​​canada​​ ​​=​​ ​​life[0]
 >>>​​ ​​canada[1]​​ ​​=​​ ​​80.0
 >>>​​ ​​canada
 ['Canada', 80.0]
 >>>​​ ​​life
 [['Canada', 80.0], ['United States', 75.5], ['Mexico', 72.0]]
Назад: List Methods
Дальше: Splitting Strings