高效地比较/整合Python列表

高效地比较/整合Python列表,python,performance,list,Python,Performance,List,我有一张这样的清单 list[0][0]="CatA" list[0][1]="SubCatA" list[0][2]="3,4" list[1][0]="CatB" list[1][1]="SubCatA" list[1][2]="1,2" list[2][0]="CatA" list[2][1]="SubCatA" list[2][2]="5,9" list[3][0]="CatA" list[3][1]="SubCatB" list[3][2]="4,7" 如果列表[x][1]相等

我有一张这样的清单

list[0][0]="CatA"
list[0][1]="SubCatA"
list[0][2]="3,4"

list[1][0]="CatB"
list[1][1]="SubCatA"
list[1][2]="1,2"

list[2][0]="CatA"
list[2][1]="SubCatA"
list[2][2]="5,9"

list[3][0]="CatA"
list[3][1]="SubCatB"
list[3][2]="4,7"
如果列表[x][1]相等且列表[x][2]相等,则Concat字段列表[x][2] 所以结果必须是这样的

list[0][0]="CatA"
list[0][1]="SubCatA"
list[0][2]="3,4,5,9"

list[1][0]="CatB"
list[1][1]="SubCatA"
list[1][2]="1,2"

list[3][0]="CatA"
list[3][1]="SubCatB"
list[3][2]="4,7"
我的代码看起来像

for y in range(len(arr)):
    print(y)
    print(arr[y])
    for z in range(len(arr)):
        print("{}.{}".format(y,z))
        if (y!=z) and (arr[y][0]!=-1) and (arr[y][0]==arr[z][0]) and (arr[y][1]==arr[z][1]):
            arr[y][2]="{},{}".format(arr[y][2],arr[z][2])
            #arr.pop(z) //first approach but error because cannot delete while iterating
            arr[z][0]=-1

print(arr)

res= []
for y in range(len(arr)):
    if (arr[y][0]==-1):
        print("nothing");
    else:
        res.append(arr[y])

print(res)
问题:这在大型arr[]上非常无效。我的arr列表长度大于2000,所以我需要运行2*2000*2000循环体

有谁有更好的方法来完成这项工作吗?

使用dict或类似dict进行高效查找:

>>> import collections
>>> 
>>> result = []
>>> 
>>> def extend_result():
...     result.append([*record[:2], []])
...     return result[-1][2]
... 
>>> uniquizer = collections.defaultdict(extend_result)
>>> 
>>> for record in arr:
...     uniquizer[tuple(record[:2])].append(record[2])
... 
>>> for record in result:
...     record[2] = ','.join(record[2])
... 
>>> result
[['CatA', 'SubCatA', '3,4,5,9'], ['CatB', 'SubCatA', '1,2'], ['CatA', 'SubCatB', '4,7']]

您可以尝试仅使用一个回路的手动方法:

con_list={}

data_=[['CatA', 'SubCatA', '3,4'], ['CatB', 'SubCatA', '1,2'], ['CatA', 'SubCatA', '5,9'], ['CatA', 'SubCatB', '4,7']]

for i in data_:
    if (i[0],i[1]) not in con_list:
        con_list[(i[0],i[1])]=i
    else:
        con_list[(i[0],i[1])]=[i[0],i[1]]+["".join([con_list[(i[0],i[1])][-1]]+[',']+[i[-1]])]

print(list(con_list.values()))
输出:

[['CatA', 'SubCatB', '4,7'], ['CatA', 'SubCatA', '3,4,5,9'], ['CatB', 'SubCatA', '1,2']]

对列表进行排序,然后使用所选索引进行分组。通常,如果您有rangelen。。。在您的代码中,您应该深入研究iterables和for循环的主题。