python中把嵌套的列表合并成一个列表方法总结
作者:起不好名字就不起了 时间:2022-06-07 04:11:22
方法一:巧用sum函数
将list列表与一个空列表相加,就能把嵌套列表合并成一个
a=[[1],[2],[3],[4],[5]]
merge=sum(a,[])
print('sum result:',merge)
结果:
sum result: [1, 2, 3, 4, 5]
方法二:使用itertools 模块的链式拼接
itertools.chain()与itertools.chain.from_iterable()函数都可以拼接可迭代对象中的所有元素,将元素串联后创建一个新的迭代器。区别是前者可用于拼接多个嵌套列表,后者拼接单个嵌套列表,示例如下。
使用itertools.chain():
import itertools
a='abc'
b='def'
merge=itertools.chain(a,b)
result = list(merge)
print('itertools.chain result:',result)
结果:
itertools.chain result: ['a', 'b', 'c', 'd', 'e', 'f']
使用itertools.chain.from_iterable():
import itertools
a=[[1],[2],[3],[4],[5]]
merge=itertools.chain.from_iterable(a)
result = list(merge)
print('itertools.chain.from_iterable result:',result)
结果:
itertools.chain.from_iterable result: [1, 2, 3, 4, 5]
方法三:迭代判断条件
遍历list内的每一个元素,如果该元素不是列表或元组就加到生成器里,如果是可迭代对象就继续递归调用,直到把所有子列表都打散,最终返回一个大列表。
def flat(l):
for k in l:
if not isinstance(k, (list, tuple)):
yield k
else:
yield from flat(k)
a=[[1],[2],[3],[4],[5]]
print ('flat result:',list(flat(a)))
结果:
flat result: [1, 2, 3, 4, 5]
方法四:简单粗暴的字符串替代
直接把整个list转换成字符串,然后替换掉边框,最后通过eval函数再转回list格式
a=[[1],[2],[3],[4],[5],[['m'],['n']]]
result = eval('[%s]'%repr(a).replace('[', '').replace(']', ''))
print('eval result:',result)
结果:
eval result: [1, 2, 3, 4, 5, 'm', 'n']
附加一道有意思的面试题
list_info = [1,2,3,4,5]
print(list_info[10:])
会输出什么?为什么?
1)导致 IndexError
2)输出[1,2,3,4,5]
3)编译错误
4)输出[]
总结
来源:https://blog.csdn.net/qq_38017966/article/details/119272263
标签:python,嵌套列表,合并
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
对Python3之方法的覆盖与super函数详解
2023-08-25 19:05:28
![](https://img.aspxhome.com/file/2023/8/107268_0s.jpg)
python中的代码编码格式转换问题
2022-02-26 02:05:02
python3调用R的示例代码
2021-05-01 21:53:59
pytorch常用数据类型所占字节数对照表一览
2021-07-25 15:26:29
python远程登录代码
2022-09-12 15:48:15
python安装sklearn模块的方法详解
2023-08-01 17:23:48
![](https://img.aspxhome.com/file/2023/9/61969_0s.jpg)
浅谈python函数之作用域(python3.5)
2021-09-22 05:49:42
Python设计模式之组合模式原理与用法实例分析
2023-04-12 16:15:28
![](https://img.aspxhome.com/file/2023/3/95563_0s.png)
Numpy中转置transpose、T和swapaxes的实例讲解
2022-09-04 21:11:10
Python序列对象与String类型内置方法详解
2023-09-22 13:25:18
Linux操作系统中如何安装MySQL数据库
2007-10-26 15:58:00
Python内置函数 next的具体使用方法
2023-09-30 18:42:28
python掌握字符串只需这一篇就够了
2023-01-09 03:39:10
php引用地址改变变量值的问题
2023-11-14 12:41:31
可以在线创建文件夹吗?
2009-11-01 18:07:00
python sys.argv[]用法实例详解
2023-10-15 17:21:55
![](https://img.aspxhome.com/file/2023/5/109955_0s.png)
详解如何将python3.6软件的py文件打包成exe程序
2022-09-26 00:10:21
![](https://img.aspxhome.com/file/2023/7/99447_0s.jpg)
Yahoo! BrowserPlus 发布
2008-11-20 13:35:00
AJAX请求类下载
2007-08-23 08:33:00
Python 安装setuptools和pip工具操作方法(必看)
2023-11-06 11:46:07
![](https://img.aspxhome.com/file/2023/1/65091_0s.png)