python - 如果一行中有特定值,则添加 2d 列表的列

标签 python

假设我有一个二维列表:

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/

相关文章:

python - Pyglet OpenGL绘图抗锯齿

使用 Docker 时找不到 Python 模块

python - 从数据库中写入和读取最新(按日期)的行

python - 如何使用 Tox 和 Poetry 在 CircleCI 中设置多个解释器?

python - 计算 SHA-1 摘要时 Python 和 C++ 中的不同结果

python - 为什么 DictWriter 在我的代码中不起作用?

python - 使用 plotly 修改轴范围

python - 如何确保 python 函数不依赖于外部变量?

Python Peewee - 将 Peewee 合并到具有缺少 ID AUTO_INCREMENT 字段的表的现有数据库中

python - 有没有pytorch方法来检查cpu的数量?