single
Working with Nested Lists in Python
メニューを表示するにはスワイプしてください
Items within a list in Python can also be lists. This forms what is called a "nested list" or "lists within lists." Nested lists are powerful in organizing elaborative data structures in that you can store multiple-level data within one list.
For instance, you might have a list where some elements are just single values, and others might be lists themselves. Here's a simple example:
123cities = ["London", ["Paris", "Madrid"], "Rome", ["Bangkok", ["New York", "Los Angeles"]]] print(cities)
Using Variables for Nested Lists
This example illustrates a nested list in which the second and fourth elements are also lists, and the fourth element even contains another nested list within it.
You can also create nested lists by concatenating lists held in variables. This can be useful to make your code more readable. For instance:
1234567europe_cities = ["Paris", "Berlin", "Rome"] asia_cities = ["Tokyo", "Seoul", "Bangkok"] america_cities = ["New York", "Los Angeles", "Chicago"] world_cities = [europe_cities, asia_cities, america_cities] print(world_cities)
Here, we first define three independent lists for cities in Europe, Asia, and the Americas. We then combine the lists into one, world_cities, which becomes a nested list.
The example shows that a nested list is a good way to organize related data, such as cities from different continents, in a natural, intuitive, and organized manner.
スワイプしてコーディングを開始
Fill the travel_wishlist list with nested lists.
- Each nested list should contain 3 elements: City, Country, and approximate trip cost.
- The
travel_wishlistlist should contain 3 nested lists with information about cities.
For example, you can use the following data:
1. Paris | France | 2000
2. Tokyo | Japan | 3500
3. Berlin | Germany | 3400
解答
フィードバックありがとうございます!
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください