aypy :
I am a beginner in python and I have this problem that I am hoping that someone could help me with.
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]...]
Chris Doyle :
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.
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]]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=291699&siteId=1