[英]How to create list of lists from sublists with varying length
I am a beginner in python and I have this problem that I am hoping that someone could help me with.我是 python 的初学者,我有这个问题,我希望有人可以帮助我。
first, I have a list of sublists with varying length首先,我有一个不同长度的子列表列表
input:输入:
temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
I am trying to create a new list of lists, where the sublist consists of items of the same index from each list sublist, I hope this does not sound too convoluted.我正在尝试创建一个新的列表列表,其中子列表由每个列表子列表中相同索引的项目组成,我希望这听起来不会太复杂。
maybe this will make it a bit more clear也许这会让它更清楚一点
desired output:所需的输出:
[[87.33372, 86.30815, 96.31665],[300.0, 300.0]]
I have thought of this formula but I'm not sure on how to implement it我已经想到了这个公式,但我不确定如何实现它
x=0
new_list = [sublist[x][i],sublist[x+1][i]...]
You can use itertools.zip_longest
with unpacking that helps you extract columns through the full length of sublists:您可以将itertools.zip_longest
与解包一起使用,帮助您通过子列表的全长提取列:
from itertools import zip_longest
temp_list = [[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
result = [list(filter(lambda x: x is not None, x)) for x in zip_longest(*temp_list)]
# [[87.33372, 86.30815, 96.31665], [300.0, 300.0]]
I would recommend the same answer as Austin and i suggest its the cleanest however as a more verbose alternative which should easily illustrate whats happening in the code you could use the following.我会推荐与 Austin 相同的答案,我建议它是最干净的,但是作为更详细的替代方案,它应该可以轻松说明您可以使用以下代码中发生的事情。
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)
OUTPUT输出
[[87.33372, 86.30815, 96.31665], [300.0, 300.0]]
You already have one loop you would just need a second你已经有了一个循环,你只需要一秒钟
This isn't the cleaned code in the world but it will do, you first calculate the max length which is basically the number of lists that the returned_list would have , create a return list ( a list of empty lists ) , then append each item when needed这不是世界上清理过的代码,但它会做,您首先计算最大长度,这基本上是返回列表将拥有的列表数,创建一个返回列表(空列表的列表),然后附加每个项目需要的时候
temp_list=[[87.33372], [86.30815, 300.0], [96.31665, 300.0]]
max_length = max([len(i) for i in temp_list])
returned_list = [[] for i in range(max_length)]
for item in temp_list:
for i in range(max_length):
try:
returned_list[i].append(item[i])
except IndexError as ie:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.