阅读两个列表并将其映射到字典中

时间:2019-12-05 06:18:28

标签: python-3.x list dictionary mapping grouping

我所拥有的

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}

我并不是特别希望有人给我答案(尽管会感激)。因此,如果有人可以向我指出正确的方向,或者给我一些话题进行探讨,那将是很好的。

2 个答案:

答案 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)

这是您应该做的

  1. list_1中取出唯一元素。提示:使用set()函数。
  2. 浏览第1步中找到的唯一商品列表。
  3. 对于找到的每个索引,将list_2中的相应值相加并求平均值。
  4. 将唯一项的值与步骤3中的平均值一起存储在字典中。

希望这对您有帮助!