user2958457
user2958457

Reputation: 55

appending list of numbers to new list python

This is kind of hard to describe so I'll show it mainly in code. I'm taking a List of a List of numbers and appending it to a masterList.
The first list in master list would be the first element of each list. I would insert 0 in it's appropriate index in the master list. Then I would move on to the next list. I would choose the first element of the 2nd list and append it to the second list in the master list, since it's index would be 1, I would insert 0 to the first index of that list. This is WAY confusing, please comment back if you have any questions about it. I'll answer back fast. This is really bugging me.

ex:

L = [[], [346], [113, 240], [2974, 1520, 684], [169, 1867, 41, 5795]]

What i want is this:

[[0,346,113,2974,169],[346,0,240,1520,1867],[113,240,0,684,41],[2974,1520,684,0,5795],[169,1867,41,5795,0]]

Upvotes: 1

Views: 75

Answers (1)

DSM
DSM

Reputation: 352969

IIUC, you want something like

>>> L = [[], [346], [113, 240], [2974, 1520, 684], [169, 1867, 41, 5795]]
>>> [x+[0]+[L[j][i] for j in range(i+1, len(L))] for i, x in enumerate(L)]
[[0, 346, 113, 2974, 169], [346, 0, 240, 1520, 1867], 
[113, 240, 0, 684, 41], [2974, 1520, 684, 0, 5795], 
[169, 1867, 41, 5795, 0]]

which might be easier to read in expanded form:

combined = []
for i, x in enumerate(L):
    newlist = x + [0]
    for j in range(i+1, len(L)):
        newlist.append(L[j][i])
    combined.append(newlist)

Upvotes: 1

Related Questions