📜  Python中的嵌套列表理解

📅  最后修改于: 2022-05-13 01:55:50.115000             🧑  作者: Mango

Python中的嵌套列表理解

列表理解是Python最令人惊奇的特性之一。这是一种通过迭代可迭代对象来创建列表的聪明而简洁的方法。嵌套列表推导只不过是另一个列表推导中的列表推导,这与嵌套 for 循环非常相似。

让我们看一些例子来了解嵌套列表推导可以做什么:

示例 1:

I want to create a matrix which looks like below:

matrix = [[0, 1, 2, 3, 4],
          [0, 1, 2, 3, 4],
          [0, 1, 2, 3, 4],
          [0, 1, 2, 3, 4],
          [0, 1, 2, 3, 4]]

以下代码对给定任务使用嵌套 for 循环:

matrix = []
  
for i in range(5):
      
    # Append an empty sublist inside the list
    matrix.append([])
      
    for j in range(5):
        matrix[i].append(j)
          
print(matrix)
输出:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

使用嵌套列表推导可以在一行中实现相同的输出:

# Nested list comprehension
matrix = [[j for j in range(5)] for i in range(5)]
  
print(matrix)
输出:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

解释:

示例 2:

Suppose I want to flatten a given 2-D list:

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

Expected Output: flatten_matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]

这可以使用嵌套的 for 循环来完成,如下所示:

# 2-D List
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
  
flatten_matrix = []
  
for sublist in matrix:
    for val in sublist:
        flatten_matrix.append(val)
          
print(flatten_matrix)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

同样,这可以使用嵌套列表理解来完成,如下所示:

# 2-D List
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
  
# Nested List Comprehension to flatten a given 2-D matrix
flatten_matrix = [val for sublist in matrix for val in sublist]
  
print(flatten_matrix)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

解释:

示例 3:

这可以使用嵌套 for 循环中的 if 条件来完成,如下所示:

flatten_matrix = [val
                  for sublist in matrix
                  for val in sublist]
输出:
# 2-D List of planets
planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']]
  
flatten_planets = []
  
for sublist in planets:
    for planet in sublist:
          
        if len(planet) < 6:
            flatten_planets.append(planet)
          
print(flatten_planets)

这也可以使用嵌套列表推导来完成,如下所示:

['Venus', 'Earth', 'Mars', 'Pluto']
输出:
# 2-D List of planets
planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']]
  
# Nested List comprehension with an if condition
flatten_planets = [planet for sublist in planets for planet in sublist if len(planet) < 6]
          
print(flatten_planets)

解释: