Xiang Yu Li Xiang Yu Li - 7 months ago 8
Python Question

I want to append the whole list to each other

totalpair = [[350, 1], [731, 1], [1441, 985], [327, 1], [1152, 985], [1593, 985], [1459, 985], [1735, 1616], [1703, 1616], [586, 1]]
totalprob = [0.0010193679918450561, 0.0010193679918450561, 0.0011627906976744186, 0.0010193679918450561, 0.0011627906976744186, 0.0011627906976744186, 0.0011627906976744186, 0.0029940119760479044, 0.0029940119760479044, 0.0011627906976744186]


I want to append the each totalprob's entry mapped into the totalpair one by one. and my code is :
for i in range(len(totalpair)):
final = final.append(totalpair[i].append(totalprob[i]))
print(final)

Answer

Using list comprehension:

final_list = list(totalpair)
[x.append(y) for x,y in zip(final_list, totalprob)]
print final_list

This will give you a list like this

[[350, 1, 0.0010193679918450561], [731, 1, 0.0010193679918450561], [1441, 985, 0.0011627906976744186], [327, 1, 0.0010193679918450561], [1152, 985, 0.0011627906976744186], [1593, 985, 0.0011627906976744186], [1459, 985, 0.0011627906976744186], [1735, 1616, 0.0029940119760479044], [1703, 1616, 0.0029940119760479044], [586, 1, 0.0011627906976744186]]

If you don't care for the original totalpair list you can avoid the full copy of the list and just update totalpair in place.

Comments