Eri*_*ika 16 python dictionary
如果我有这种类型的字典:
a_dictionary = {"dog": [["white", 3, 5], ["black", 6,7], ["Brown", 23,1]],
"cat": [["gray", 5, 6], ["brown", 4,9]],
"bird": [["blue", 3,5], ["green", 1,2], ["yellow", 4,9]],
"mouse": [["gray", 3,4]]
}
Run Code Online (Sandbox Code Playgroud)
我想从第一行 3 与 6 和 23 求和,在下一行 5 与 4 等求和,这样打印时我会得到:
dog [32, 13]
cat [9, 15]
bird [8, 16]
mouse [3,4]
Run Code Online (Sandbox Code Playgroud)
我尝试了a_dictionary 范围的for 循环来按索引求和,但随后我无法通过以下键访问值:a_dictionary[key]
但是,如果我像这样循环遍历 a_dictionary for key, value in a dictionary.items():,我无法通过索引访问它来总结所需的值。
我很想看看如何实现这一点。谢谢。
And*_*ely 22
通常,在 Python 中,您不想使用索引来访问列表或其他可迭代对象中的值(当然这并不总是适用)。
通过巧妙地使用zip()和 ,map()您可以对适当的值求和:
a_dictionary = {
"dog": [["white", 3, 5], ["black", 6, 7], ["Brown", 23, 1]],
"cat": [["gray", 5, 6], ["brown", 4, 9]],
"bird": [["blue", 3, 5], ["green", 1, 2], ["yellow", 4, 9]],
"mouse": [["gray", 3, 4]],
}
for k, v in a_dictionary.items():
print(k, list(map(sum, zip(*(t for _, *t in v)))))
Run Code Online (Sandbox Code Playgroud)
印刷:
dog [32, 13]
cat [9, 15]
bird [8, 16]
mouse [3, 4]
Run Code Online (Sandbox Code Playgroud)
编辑:
我将从(t for _, *t in v)列表中提取最后两个值(丢弃第一个字符串值)
[3, 5], [6, 7], [23, 1]
[5, 6], [4, 9]
[3, 5], [1, 2], [4, 9]
[3, 4]
Run Code Online (Sandbox Code Playgroud)
zip(*...)是一个转置操作
(3, 6, 23), (5, 7, 1)
(5, 4), (6, 9)
(3, 1, 4), (5, 2, 9)
(3,), (4,)
Run Code Online (Sandbox Code Playgroud)
然后我应用sum()到步骤 2 中创建的每个子列表。map()
32, 13
9, 15
8, 16
3, 4
Run Code Online (Sandbox Code Playgroud)
的结果map()存储到列表中
小智 7
您可以使用 Python 的列表理解来创建每种颜色的索引元素的临时列表并对其进行求和,例如:
for animal, colors in a_dictionary.items():
print(
animal,
[
sum([color[1] for color in colors]),
sum([color[2] for color in colors]),
]
)
Run Code Online (Sandbox Code Playgroud)
for key, value in my_dictionary.items():
sum_1, sum_2 = 0, 0
for sublist in value:
sum_1 += sublist[1]
sum_2 += sublist[2]
print(key, [sum_1, sum_2])
Run Code Online (Sandbox Code Playgroud)
小智 5
这对我有用:
results = {}
sum_x = 0
sum_y = 0
for key,value in a_dictionary.items():
for i in range(len(value)):
sum_x += value[i][1]
sum_y += value[i][2]
results[key] = [sum_x,sum_y]
sum_x = 0
sum_y = 0
Run Code Online (Sandbox Code Playgroud)
输出:
results
{'dog': [32, 13], 'cat': [9, 15], 'bird': [8, 16], 'mouse': [3, 4]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1055 次 |
| 最近记录: |