是)我有的
list_1 = ["5","1","6","1","2","5"]
list_2 = ["1","3","9","15","16","16"]
请注意列表中的重复项
我想要的是
我正在尝试创建一个字典,其中列表1中的唯一值是键,列表2中相应元素的平均值是值。
换句话说,我遵循的字典如下:
{"1": 9.0, "2": 16, "5": 8.5, "6": 9.0}
我不是专门找人给我答案(尽管会感激)。因此,如果有人可以向我指出正确的方向,或者给我一些主题进行研究,那将是很好的。
这是使用循环的手动方法,这应该解释逻辑流程。
# Two lists
list_1 = ["5","1","6","1","2","5"]
list_2 = ["1","3","9","15","16","16"]
# Empty dictionary
results ={}
# Go through list on, create a key in the dict if the key does not exist
# Then add the value to the array identified by that key
# Cast to int to make life easier
for i in range(0, len(list_1)):
if (not list_1[i] in results):
results[list_1[i]] = []
results[list_1[i]].append(int(list_2[i]))
# Print the results before you average it
print(results)
# >> {'5': [1, 16], '1': [3, 15], '6': [9], '2': [16]}
# Iterate through all keys and average the values, assigning the result to that key
for k in results:
results[k] = (sum(results[k])/len(results[k]))
print(results)
# >> {'5': 8.5, '1': 9.0, '6': 9.0, '2': 16.0}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句