📜  Python|列表的分组展平

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

Python|列表的分组展平

扁平化列表的问题很常见,但有时,我们需要以分组的方式执行扁平化,即获取大小为 K 的子列表并将它们扁平化。这个特殊的实用程序在许多领域都有用例,包括 Web 开发和日常编程。让我们讨论一些可以做到这一点的方法。

方法#1:使用列表理解+列表切片
这个问题可以通过使用列表推导和应用列表切片来限制分组和绑定列表作为列表推导逻辑的一部分来解决。

# Python3 code to demonstrate 
# group flattening of list 
# using list comprehension + list slicing
  
# initializing list of lists
test_list = [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
  
# printing original list 
print("The original list : " +  str(test_list))
  
# declaring K 
K = 3
  
# using list comprehension + list slicing
# group flattening of list 
res = [[i for sub in test_list[j : j + K] for i in sub]
                  for j in range(0, len(test_list), K)]
  
# printing result 
print("The grouped flattened list :  " + str(res))
输出 :
The original list : [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
The grouped flattened list :  [[1, 3, 3, 4, 6, 5], [4, 5, 7, 6, 7, 9]]

方法 #2:使用列表理解 + zip() + map()
这个问题也可以通过以上3个功能的组合来解决。 zip函数用于将所有组合二为一,map函数用于将迭代器转换为列表,列表推导式执行分组任务。

# Python3 code to demonstrate 
# group flattening of list 
# using list comprehension + zip() + map()
  
# initializing list of lists
test_list = [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
  
# printing original list 
print("The original list : " +  str(test_list))
  
# declaring K 
K = 3
  
# using list comprehension + zip() + map()
# group flattening of list 
res = list(map(list, zip(*[iter([i for sub in test_list
              for i in sub])]*(K * len(test_list[0])))))
  
# printing result 
print("The grouped flattened list :  " + str(res))
输出 :
The original list : [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
The grouped flattened list :  [[1, 3, 3, 4, 6, 5], [4, 5, 7, 6, 7, 9]]