我有一个像
这样的清单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"
Concat字段列表[x] [2]如果列表[x] [1]相等且列表[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循环体。
任何人都有更好的方法来完成这项工作吗?
答案 0 :(得分:1)
使用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']]
答案 1 :(得分:0)
您只需一个循环就可以尝试手动方法:
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']]