我所拥有的
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}
我并不是特别希望有人给我答案(尽管会感激)。因此,如果有人可以向我指出正确的方向,或者给我一些话题进行探讨,那将是很好的。
答案 0 :(得分:1)
这里有一种手动处理循环的方法,应该可以解释逻辑流程。
# 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}
答案 1 :(得分:0)
这是您应该做的
list_1
中取出唯一元素。提示:使用set()
函数。list_2
中的相应值相加并求平均值。希望这对您有帮助!