Python多维列表(元组)合并成一维形式

简介: 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函数

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 类库

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
相关文章
|
6月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
392 1
|
7月前
|
缓存 监控 数据可视化
微店item_search - 根据关键词取商品列表深度分析及 Python 实现
微店item_search接口可根据关键词搜索商品,返回商品信息、价格、销量等数据,适用于电商检索、竞品分析及市场调研。接口需通过appkey与access_token认证,支持分页与排序功能,Python示例代码实现调用流程,助力商品数据高效获取与分析。
|
6月前
|
开发者 Python
Python列表推导式:优雅与效率的完美结合
Python列表推导式:优雅与效率的完美结合
507 116
|
6月前
|
大数据 开发者 Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
448 109
|
6月前
|
Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
520 119
|
6月前
|
开发者 Python
Python列表推导式:优雅与效率的完美融合
Python列表推导式:优雅与效率的完美融合
372 104
|
6月前
|
Python
Python列表推导式:优雅与效率的艺术
Python列表推导式:优雅与效率的艺术
374 99
|
6月前
|
数据处理 Python
解锁Python列表推导式:优雅与效率的完美融合
解锁Python列表推导式:优雅与效率的完美融合
396 99
|
6月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
527 95
|
7月前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
614 99

推荐镜像

更多