深度阅读

How to flatten a nested list in Python

作者
作者
2023年08月22日
更新时间
9.29 分钟
阅读时间
0
阅读量

To flatten a nested list in Python, you can use various approaches. One simple approach is to use a list comprehension that iterates over the nested lists and adds the elements to a new flattened list. Here is an example:

nested_list = [[1, 2], [3, 4, 5], [6]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)

This will output [1, 2, 3, 4, 5, 6].

Alternatively, you can use the itertools module to chain the nested lists together as follows:

import itertools

nested_list = [[1, 2], [3, 4, 5], [6]]
flattened_list = list(itertools.chain.from_iterable(nested_list))
print(flattened_list)

This will also output [1, 2, 3, 4, 5, 6].

These are just a couple of examples of how to flatten a nested list in Python. There are other approaches you can use depending on your specific use case. I hope this helps! Let me know if you have any further questions.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。