简体   繁体   English

将数字列表附加到新列表python

[英]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. 我正在获取数字列表的列表,并将其附加到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. 我会在主列表的适当索引中插入0。 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. 我会选择第二个列表的第一个元素,并将其附加到主列表的第二个列表中,因为它的索引为1,所以我将0插入该列表的第一个索引。 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]]

IIUC, you want something like IIUC,您想要类似

>>> 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM