如何使用字典替换列表中的数字?



假设我们有一个大小为10的1向量。如何编写一个键为index,值为replacing_number的代码?如:

Vector = [1,1,1,1,1,1,1,1,1,1]
Dict = {2:4, 6:9, 9:3}
Output will be [1,4,1,1,1,9,1,1,3,1]

您可以尝试以下操作:

for key, value in Dict.items():
Vector[key-1] = value

注意我要减去1,因为你的字典似乎从1开始计数,但python从0开始计数。

Vector = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Dict = {2: 4, 6: 9, 9: 3}
for k, v in Dict.items():
Vector[k - 1] = v
print(Vector)
# output: [1, 4, 1, 1, 1, 9, 1, 1, 3, 1]
for k in d:
if k > 0 and k <= len(v):
v[k - 1] = d[k]

你可以像上面那样尝试在字典中循环。希望对你有帮助另外,你的输出不正确

Output will be [1,4,1,1,1,9,1,1,4,1]
it should be   [1,4,1,1,1,9,1,1,3,1]

最新更新