簡體   English   中英

Python:如何組合二維數組中的元素?

[英]Python: how to combine elements in a 2d array?

我有這個清單

[[0, 185], [0, 374], [0, 676], [0, 844], [1, 186], [1, 440], [2, 202], [3, 198], [3, 571], ...]

我希望它是這樣的:

[[0, 374,676,844], [1, 186, 440],[2, 202], [3, 198, 571], ...]

我試過這個代碼:

for i in range(len(index)-1):
    if (index[i][0]==index[i+1][0]):
        index[i].append(index[i+1][1])
        del index[i+1]
        i=i-1

但它不起作用

一般來說,不建議從您正在迭代的列表中刪除項目。 在 Python 中,生成具有理解性的新列表更常見(也更容易)。

您可以使用itertools.groupby進行分組,並按列表中的第一項分組。 然后從這些組中,您可以通過獲取鍵加上所有其他第二個元素來創建所需的子組。 就像是:

from itertools import groupby

l = [[0, 185], [0, 374], [0, 676], [0, 844], [1, 186], [1, 440], [2, 202], [3, 198], [3, 571]]

[[k] + [i[1] for i in g] for k, g in groupby(l, key=lambda x: x[0])]
# [[0, 185, 374, 676, 844], [1, 186, 440], [2, 202], [3, 198, 571]]

這是一個更簡單的解決方案:

lst = [[0, 185], [0, 374], [0, 676], [0, 844], [1, 186], [1, 440], [2, 202], [3, 198], [3, 571]]
newlst = []
curr_lst = []
max_index = 3

for x in range(max_index+1):
    
    curr_lst = [x]
    
    for y in lst:
        if y[0] == x:
            curr_lst.append(y[1])
    newlst.append(curr_lst)
    
print(newlst)

輸出:

[[0, 185, 374, 676, 844], [1, 186, 440], [2, 202], [3, 198, 571]]

最簡單的實現方式。 在使用該函數之前,請確保您已按子列表的第一個索引對列表進行排序。

a = [[0, 185], [0, 374], [0, 676], [0, 844], [1, 186], [1, 440], [2, 202], [3, 198], [3, 571]]
    
    n = len(a)
    x = 0
    res = []
    r = [0]
    for i in a:
        if i[0] == x:
            r.append(i[1])
        else:
            x += 1
            res.append(r)
            r = [x, i[1]]
    res.append(r)
    print(res)

使用集合 OrderedDict

 from collections import OrderedDict

l = [[0, 185], [0, 374], [0, 676], [0, 844], [1, 186], [1, 440], [2, 202], [3, 198], [3, 571]]
d = OrderedDict()
for inner in l:
    if inner[0] in d:
        d[inner[0]].append(inner[1])
    else:
        d[inner[0]] = [inner[1]]

print(d.values())

您可以使用字典從輸入列表中收集索引 1 中的數字。

a=[[0, 185], [0, 374], [0, 676], [0, 844], [1, 186], [1, 440], [2, 202], [3, 198], [3, 571]]
b={}

[b[i[0]].append(i[1]) if i[0] in b else b.update({i[0]:[i[0],i[1]]}) for i in a]
b=list(b.values())

print(b)

輸出

[[0, 185, 374, 676, 844], [1, 186, 440], [2, 202], [3, 198, 571]]

無需導入,您可以通過以下方式進行 -

new_dict = {}
result = []

for item in nest:
    if item[0] in new_dict.keys():
        new_dict[item[0]].append(item[1])
    else:
        new_dict[item[0]] = [item[1]]

for key, value in new_dict.items():
    result.append([key] + value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM