模拟数据

data = [[1,2,6],[4],[5,8,7],[11,9],[10]]  # 模拟数据

  

方式1:for循环

from collections.abc import Iterable
sum_data = [] for i in data: if isinstance(i,Iterable): # 如果可迭代(比如列表形式) for j in i: # 再次循环追加元素 sum_data.append(j) else: sum_data.append(i) # 否则直接追加 #sum_data #[1, 2, 6, 4, 5, 8, 7, 11, 9, 10]

 

方式2:列表推导式

from collections.abc import Iterable
sum_data = [i for j in data  if isinstance(j,Iterable) for i in j]
#[1, 2, 6, 4, 5, 8, 7, 11, 9, 10]

  

方式3:使用sum函数

sum_data = sum(data, [])
#sum_data
#[1, 2, 6, 4, 5, 8, 7, 11, 9, 10]

 

 

 

 posted on 2024-04-10 17:36  boye169  阅读(2)  评论(0编辑  收藏  举报