Hướng Dẫn Create list of lists Python Chi tiết

Kinh Nghiệm Hướng dẫn Create list of lists Python 2022

Pro đang tìm kiếm từ khóa Create list of lists Python được Cập Nhật vào lúc : 2022-01-05 01:05:18 . Với phương châm chia sẻ Bí kíp Hướng dẫn trong nội dung bài viết một cách Chi Tiết Mới Nhất. Nếu sau khi đọc Post vẫn ko hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Tác giả lý giải và hướng dẫn lại nha.

In this tutorial, youll learn how to use Python to flatten lists of lists! Youll learn how to do this in a number of different ways, including with for-loops, list comprehensions, the itertools library, and how to flatten multi-level lists of lists using, wait for it, recursion! Lets take a look what youll learn in this tutorial!

Nội dung chính

    What is a Python List of Lists?How to Use a Python For Loop to Flatten Lists of Lists?How to Use a List Comprehension in Python to Flatten Lists of Lists?How to Use Itertools to Flatten Python Lists of ListsHow to Flatten Multi-level Lists of Lists in Python?

The Quick Answer: Use a Python List Comprehension to Flatten Lists of Lists

Use list comprehensions to flatten lists of lists in Python

Table of Contents

    What is a Python List of Lists?How to Use a Python For Loop to Flatten Lists of Lists?How to Use a List Comprehension in Python to Flatten Lists of Lists?How to Use Itertools to Flatten Python Lists of ListsHow to Flatten Multi-level Lists of Lists in Python?Conclusion

What is a Python List of Lists?

In Python, a list of a lists is simply a list that contains other lists. In fact, lists of lists in Python can even contain other lists of lists! We can say that a list that contains only one other layer of lists is called a 2-dimensional list of lists. When one or more of these lists contain another list, we say theyre called 3-dimensional. This continues onwards, as we add more and more layers.

When you convert a list of lists, or a 2-dimensional array, into a one-dimensional array, you are flattening a list of lists. Learn four different ways to do this in this tutorial!

Lets take a look a simple list of lists in Python, so that you can have a visual depiction of what they actually look like:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

When we try to access the third item, index position 2, we can print out what it contains:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(list_of_lists[2])
# Returns: [4, 5, 6]

We can see here that the third item of our list list_of_lists is actually another list. This is what we mean by lists of lists they are lists that contain other lists.

In the next section, youll learn how to use a naive method, a for-loop, to flatten a list of lists.

How to Use a Python For Loop to Flatten Lists of Lists?

Now that you know what a Python list of lists is, lets see how we can use a Python for-loop to flatten them!

In our for-loop, well loop over each item in the list and add each item to a new list.

Lets see how we can accomplish this with Python:

# Use a for-loop to flatten a list of lists
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = list()
for sub_list in list_of_lists:
flat_list += sub_list
print(flat_list)
# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Lets break down what weve done here step-by-step:

We loaded our list_of_listsWe generated a new list, called flat_listWe looped over each item, or list, in the list of lists and added each items values to our flat_list

Now that youve used a for-loop to flatten a list of lists, lets learn how you can use list comprehensions to flatten them!

Want to learn more? Check out my in-depth tutorial on Python for-loops here!

How to Use a List Comprehension in Python to Flatten Lists of Lists?

Python list comprehensions are elegant, Pythonic replacements for Python for-loops. In fact, any list comprehension can actually be expressed as a for-loop (though the reverse isnt necessarily true).

So why write a list comprehension when a for-loop might do? There are a number of benefits to using list comprehensions lets take a quick look them here:

You dont need to instantiate a new empty listYou can write it over one line, rather than needing to split it out over multiple linesTheyre more Pythonic than for-loops

Want to learn more? Check out my in-depth tutorial on Python list comprehensions here!

Lets take a look how Python list comprehension look:

How to write a simple Python list comprehension

Now, lets see how we can use list comprehensions to flatten Python lists of lists:

# Use a List Comprehension to Flatten a List of Lists
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [item for sublist in list_of_lists for item in sublist]
print(flat_list)
# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Keep in mind that this does exactly what the for-loop is doing. The syntax can take a bit of getting used to, but once you master it, it becomes second nature and saves you a good amount of time!

How to Use Itertools to Flatten Python Lists of Lists

Both of the methods weve covered off so far dont require you to import a different library. Now, lets take a look how we can use the itertools library to flatten Python lists of lists.

In particular, well use the chain function to to loop over each individual item in the larger list and add it to the larger list. Finally, since the chain function would return an itertools.chain object, we need to convert it back to a list.

Let see how we can do this here:

from itertools import chain
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = list(chain(*list_of_lists))
print(flat_list)
# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Since we rely on variable unpacking, its not immediately clear whats happening in the code (as some other custom functions might). Because of this, make sure you document your code well!

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

How to Flatten Multi-level Lists of Lists in Python?

Now, there may be times that you encounter more complex lists, such as the one shown below. Using one of these methods shown above wont work, as they require you to have similar levels within their lists.

list_of_lists = [1, [2, 3], [4, [5, 6]], [7, 8], 9]

We can see that in our lists, we have some items the root level, and some lists embedded in other lists.

In order to flatten this list of lists, we will need to think a bit more creatively. In particular, we can develop a function that calls itself recursively to unpack lists of lists.

Lets see how we can do this in Python:

# Flatten a multi-level list of lists with recursion
list_of_lists = [1, [2, 3], [4, [5, 6]], [7, 8], 9]
flat_list = list()
def flatten_list(list_of_lists):
for item in list_of_lists:
if type(item) == list:
flatten_list(item)
else:
flat_list.append(item)
return flat_list
flatten_list(list_of_lists)
print(flat_list)
# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

This example is a bit more complex, so lets see what weve done here:

We instantiate an empty list, flat_list. Its important to do this outside of the function definition, since well be calling it recursively.We generate a new function flatten_list that takes an list of lists as an inputWe then loop over each item in the listWe check if the type of the item is a list:If it is a list, then we call the function againIf it isnt, we append the item to our flat_list

We can see here that this works quite simply and is actually adaptable to any number of nesting!

Conclusion

In this post, you learned how to use Python to flatten lists of lists. You also learned what lists of lists in Python actually are. In addition to this, you learned how to use for-loops and list comprehensions to flatten lists of lists in Python. You also learned how to use the itertools library to flatten lists of lists. Finally, you learned how to use recursion to multi-level lists of lists.

To learn more about the itertools library, check out the official documentation here.

Share via:

    FacebookTwitterLinkedInEmailMore

Clip Create list of lists Python ?

Bạn vừa Read Post Với Một số hướng dẫn một cách rõ ràng hơn về Review Create list of lists Python tiên tiến và phát triển nhất

Chia Sẻ Link Down Create list of lists Python miễn phí

Bạn đang tìm một số trong những Chia Sẻ Link Down Create list of lists Python Free.

Hỏi đáp vướng mắc về Create list of lists Python

Nếu sau khi đọc nội dung bài viết Create list of lists Python vẫn chưa hiểu thì hoàn toàn có thể lại Comment ở cuối bài để Tác giả lý giải và hướng dẫn lại nha
#Create #list #lists #Python

Phone Number

Recent Posts

Tra Cứu MST KHƯƠNG VĂN THUẤN Mã Số Thuế của Công TY DN

Tra Cứu Mã Số Thuế MST KHƯƠNG VĂN THUẤN Của Ai, Công Ty Doanh Nghiệp…

3 years ago

[Hỏi – Đáp] Cuộc gọi từ Số điện thoại 0983996665 hoặc 098 3996665 là của ai là của ai ?

Các bạn cho mình hỏi với tự nhiên trong ĐT mình gần đây có Sim…

3 years ago

Nhận định về cái đẹp trong cuộc sống Chi tiết Chi tiết

Thủ Thuật về Nhận định về nét trẻ trung trong môi trường tự nhiên vạn…

3 years ago

Hướng Dẫn dooshku là gì – Nghĩa của từ dooshku -Thủ Thuật Mới 2022

Thủ Thuật về dooshku là gì - Nghĩa của từ dooshku -Thủ Thuật Mới 2022…

3 years ago

Tìm 4 số hạng liên tiếp của một cấp số cộng có tổng bằng 20 và tích bằng 384 2022 Mới nhất

Kinh Nghiệm Hướng dẫn Tìm 4 số hạng liên tục của một cấp số cộng…

3 years ago

Mẹo Em hãy cho biết nếu đèn huỳnh quang không có lớp bột huỳnh quang thì đèn có sáng không vì sao Mới nhất

Mẹo Hướng dẫn Em hãy cho biết thêm thêm nếu đèn huỳnh quang không còn…

3 years ago