python - 列表python的元素明智合并
问题描述
要合并两个列表的元素,如下所示,非常简单:
one = [['hi', 'hello'], ['namaste']]
two = [['hi', 'bye'], ['namaste']]
[m+n for m,n in zip(one,two)]
但是,如果我有一个大于长度 2 的列表,怎么办?例如,连接以下列表列表中的每个元素:
three = [['hi', 'why'], ['bye']]
list_ = [one, two, three]
我想要一个像这样的输出:[['hi', 'hello', 'hi', 'bye', 'hi', 'why'], ['namaste', 'namaste', 'bye']]
如何以可扩展的方式完成此操作,甚至可以使用list_
长度为 10 的 a?
解决方案
以下代码将缩放
from itertools import chain
out = []
for each in zip(*list_):
out.append(list(chain.from_iterable(each)))
或单班轮
print([list(chain.from_iterable(each)) for each in zip(*list_)])
推荐阅读
- git - 如何在 Git 中重新签出子模块?
- java - 读取用户输入时线程“主”java.util.NoSuchElementException 中的异常
- asp.net-identity - Blazor UserManager.GetUserAsync 抛出 NullReferenceException
- kubernetes - 由于“只读文件系统”,Google Kubernetes Engine (GKE) 集群“创建挂载源路径时出错”
- java - Java JSON String 编码 Multipart 问题
- phpmyadmin - WAMP / PHPMyAdmin 警告:不支持声明“strict_types”
- java - 我正在尝试制作一个小游戏,但我在 android 中的循环不起作用
- cordova - ionic:为 ipad 构建 ios 的问题
- sql - 如何在sql中连接多个具有不同列的表?
- jira - 无法配置 Jira 泳道