假设我有一个二维列表:
mylist = [[3,4,5,'x'],
[6,1,4,'x'],
[4,7,9,'y'],
[0,4,3,'y'],
[5,1,7,'z']]
我如何总结第四个元素(字母)相同的第二列?目前我已经将第四个元素隔离到一个列表中,避免重复,其中:
newlist = list(set([r[3] for r in mylist]))
返回一个列表 ['z', 'y', 'x']
我希望它的格式如下:[['x', a], ['y', b]..]
或像 {'x' 这样的字典:一,...
其中 a
是第二列 mylist[3]='x'
的总和,即 4+1,和 b
是相同的,但带有 y
并且是 7+4。所以这个例子会输出 [['x', 5], ['y', 11], ['z', 1]]
执行此操作的最佳方法是什么?或者 numpy/pandas 会处理得更好吗?
最佳答案
这应该可以,我正在使用 zip
mylist = [[3,4,5,'x'],
[6,1,4,'x'],
[4,7,9,'y'],
[0,4,3,'y'],
[5,1,7,'z']]
#Zip all elements in the list
res = list(zip(*mylist))
#Zip the second column and character array
arr = list(zip(res[1], res[3]))
#[(4, 'x'), (1, 'x'), (7, 'y'), (4, 'y'), (1, 'z')]
dct = {}
#Calculate the sum
for num, key in arr:
dct.setdefault(key,0)
dct[key]+=num
print(dct)
#{'x': 5, 'y': 11, 'z': 1}
#Convert dict to list
li = []
for k, v in dct.items():
li.append([k,v])
print(li)
输出将是
[['x', 5], ['y', 11], ['z', 1]]
关于python - 如果一行中有特定值,则添加 2d 列表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941603/