Python教程:多维列表(元组)碾成一维形式

一.需求

原格式:

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

目标格式:

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

二.方法

1.sum函数合并

input=[[1,2,3],[4,5,6],[7,8,9]]
output=sum(input,[])
print(output)

#结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

这个看上去很简洁,不过有类似字符串累加的性能陷阱。

2.reduce函数

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from functools import reduce

input=[[1,2,3],[4,5,6],[7,8,9]]
output=reduce(list.__add__, input)
print(output)

#结果[1, 2, 3, 4, 5, 6, 7, 8, 9]

做序列的累加操作。也是有累加的性能陷阱。

3.列表推导式

input=[[1,2,3],[4,5,6],[7,8,9]]
output=[item for sublist in input for item in sublist]
print(output)

#结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]

列表推导式,看着有些长,而且还要for循环两次,变成一行理解需要费劲一些,没有那么直观
  
4.itertools 类库

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import itertools
input=[[1,2,3],[4,5,6],[7,8,9]]
ouput=list(itertools.chain(*input))
print(ouput)

#结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]

三.性能对比

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 51.2 usec per loop

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(list.__add__,l)'
1000 loops, best of 3: 572 usec per loop
 
python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 545 usec per loop

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99; import itertools;' 'list(itertools.chain(*l))'
10000 loops, best of 3: 35.1 usec per loop

猜你喜欢

转载自blog.csdn.net/qdPython/article/details/112845587
今日推荐