gpt4 book ai didi

python - 根据列表的值匹配列表的索引

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:49 27 4
gpt4 key购买 nike

我是 Python 新手,正在解决一个问题,我必须将索引列表与具有 2 个条件的值列表进行匹配:

  1. 如果存在重复索引,则应将这些值相加
  2. 如果列表中没有索引,则值应为 0

例如,下面是我的 2 个列表:“Inds 列表”和“Vals 列表”。所以在索引 0 处,我的值为 5;在索引 1 处,我的值为 4;在索引 2 处,我的值为 3 (2+1),在索引 3 处,我的值为 0(因为没有与索引关联的值),依此类推。

Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]
Output = [5,4,3,0,3]

我已经为此苦苦挣扎了几天,但在网上找不到任何可以为我指明正确方向的内容。谢谢。

最佳答案

List_of_Inds = [0,1,4,2,2]
List_Vals = [5,4,3,2,1]
dic ={}

i = 0
for key in List_of_Inds:
if key not in dic:
dic[key] = 0
dic[key] = List_Vals[i]+dic[key]
i = i+1

output = []
for key in range(0, len(dic)+1):
if key in dic:
output.append(dic[key])
else:
output.append(0)

print(dic)
print(output)

输出:

{0: 5, 1: 4, 4: 3, 2: 3}
[5, 4, 3, 0, 3]

关于python - 根据列表的值匹配列表的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com