我正在使用列表字典:
percent = {'l1': [0, 0, 0, 0, 0, 0, 0, 0, 0],
'l2': [-16, -16, -16, -16, 0, 0, 0, 0, 0],
'l3': [0, 0, 0, 0, 0, 0, 0, 0, 0],
'l4': [0, 0, 0, 0, 0, 0, 0, 0, 0],
'l5': [0, 0, 0, 0, 0, 0, 0, 0, 0],
'l6': [0, 0, 0, 0, 0, 0, -16, 0, 0],
'l7': [0, 0, 0, 0, 0, 0, 0, 0, -48],
'l8': [0, 0, 0, 0, 0, 0, 0, -12, -20]
}
我想添加所有列表的第一个元素,并将结果存储为列表result = []的第一个元素,并分别存储其他元素?
有人可以帮我吗?
答案 0 :(得分:1)
[sum(x) for x in zip(*percent.values())]
答案 1 :(得分:0)
无需使用任何外部模块,即可非常简单地完成此操作。由于所有不同键的值中都有9个元素,因此涉及简单的迭代。
readelf -h libgame.so
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: DYN (Shared object file)
Machine: ARM
Version: 0x1
Entry point address: 0x0
Start of program headers: 52 (bytes into file)
Start of section headers: 41140616 (bytes into file)
Flags: 0x5000000, Version5 EABI
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 8
Size of section headers: 40 (bytes)
Number of section headers: 24
Section header string table index: 23
编辑:我没有使用任何外部模块/库。您可以自己尝试。
答案 2 :(得分:0)
您可以将其写为嵌套列表理解:
results = [sum([l[i] for l in percent.values()])
for i in range(len(list(percent.values())[0]))]
等同于:
results = []
for i in range(len(list(percent.values())[0])):
s = 0
for l in percent.values():
s += l[i]
results.append(s)
len(list(percent.values())[0])
用于动态查找字典中列表的长度。
答案 3 :(得分:0)
您可以通过列表理解来实现:
# length of first element
length = len(list(percent.values())[0])
sums = [sum(val[i] for val in percent.values()) for i in range(length)]
答案 4 :(得分:0)
import numpy as np
narr = np.asarray(list(percent.values()))
result = narr.sum(0)
答案 5 :(得分:-1)