python - 如何从具有不同长度的子列表创建列表列表
问题描述
我是python的初学者,我有这个问题,我希望有人可以帮助我。
首先,我有一个不同长度的子列表列表
输入:
temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
我正在尝试创建一个新的列表列表,其中子列表由每个列表子列表中相同索引的项目组成,我希望这听起来不会太复杂。
也许这会让它更清楚一点
所需的输出:
[[87.33372, 86.30815, 96.31665],[300.0, 300.0]]
我已经想到了这个公式,但我不确定如何实现它
x=0
new_list = [sublist[x][i],sublist[x+1][i]...]
解决方案
我会推荐与奥斯汀相同的答案,我建议它是最干净的,但是作为更详细的替代方案,它应该很容易说明你可以使用以下代码中发生的事情。
temp_list = [[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
new_list = []
#loop over each list
for items in temp_list:
#for each item in the sublist get its index and value.
for i, v in enumerate(items):
#If the index is greater than the length of the new list add a new sublist
if i >= len(new_list):
new_list.append([])
#Add the value at the index (column) position
new_list[i].append(v)
print(new_list)
输出
[[87.33372, 86.30815, 96.31665], [300.0, 300.0]]
推荐阅读
- python - 是否每个张量都作为 fetches 传递给评估的会话的 run 方法?
- sql - 这个左连接有什么意义?
- ios - WKWebView 页面进入透明状态栏
- c - WIN32在套接字函数arg错误中发送数据
- java - Java Spring Rest 模板未将 JSON 作为字符串发布
- python - 将exe移出dist文件夹并使其工作?
- javascript - 从对象数组中过滤一些对象
- ibm-mq - 如何解决 IBM MQ 连接中的 mqdc.dll 错误
- jmeter - 如何使用 JMeter 测试接受 XML 输入的休息端点?
- kubernetes - 如何为 EKS 配置 Terraform Kubernetes 提供程序