我是一个2D数组,想要组合部分相似的项目。
[
[Red,Blue,Yellow,5]
[Red,Blue,Yellow,10]
[Red,Blue,Green,5]
[Red,Blue,Green,5]
[Red,Blue,Orange,5]
[Red,Blue,Violet,5]
]
我希望它变成这样,修剪并创建一个独特的数组
[
[Red,Blue,Yellow,15]
[Red,Blue,Green,10]
[Red,Blue,Orange,5]
[Red,Blue,Violet,5]
]
Edit1:这就是我的所作所为。我只有基础知识,并希望有更好的版本。
newTaskList = []
totalTaskList = []
totalValueList = []
finalTaskList = []
for taskIndex, taskList in enumerate(readTaskList):
newTaskList = []
newTaskList.append(taskList[0])
newTaskList.append(taskList[1])
newTaskList.append(taskList[2])
newTaskList.append(taskList[4])
if(newTaskList not in totalTaskList):
totalTaskList.append(newTaskList)
totalValueList.append(float(taskList[3]))
else:
for itemIndex, itemList in enumerate(totalTaskList):
if(itemList[0] == taskList[0] and itemList[1] == taskList[1] and itemList[2] == taskList[2] and itemList[3] == taskList[4]):
totalValueList[itemIndex] += float(taskList[3])
for taskIndex, task in enumerate(totalTaskList):
for workType in workTypeList:
newWorkTypeItem = task[2].replace(" ","_").split("_")
if len(newWorkTypeItem) > 1:
task[2] = newWorkTypeItem[0] + " " + newWorkTypeItem[1]
if(task[1] == workType[0] and task[2] == workType[1]):
task[2] = workType[2]
break
task.append(totalValueList[taskIndex])
finalTaskList.append(task)
答案 0 :(得分:1)
您可以使用result = defaultdict(int)
for col1, col2, col3, value in my_list:
result[(col1, col2, col3)] += value
result = [list(key) + [value] for key,value in result.items()]
print(result)
。
[['Red', 'Blue', 'Yellow', 15], ['Red', 'Blue', 'Green', 10], ['Red', 'Blue', 'Orange', 5], ['Red', 'Blue', 'Violet', 5]]
输出
{{1}}
答案 1 :(得分:1)
使用集合模块。
<强>实施例强>
from collections import defaultdict
l = [
['Red','Blue','Yellow',5],
['Red','Blue','Yellow',10],
['Red','Blue','Green',5],
['Red','Blue','Green',5],
['Red','Blue','Orange',5],
['Red','Blue','Violet',5],
]
d = defaultdict(int)
for i in l:
d[tuple(i[:3])] += i[-1]
print [list(k) + [v] for k,v in d.items()]
<强>输出:强>
[['Red', 'Blue', 'Orange', 5], ['Red', 'Blue', 'Yellow', 15], ['Red', 'Blue', 'Violet', 5], ['Red', 'Blue', 'Green', 10]]