Python 3.x 每次迭代都会更改一个变量,我想将它作为键打印到字典中

Python 3.x 每次迭代都会更改一个变量,我想将它作为键打印到字典中,python-3.x,dictionary,Python 3.x,Dictionary,输入有4个值:string、int、int、int。 我想把k1的值设为key,把分数设为value。 当我尝试上述代码时,输出如下: 以下是有效的代码(对原始代码进行了非常小的修改) 如果使用1 10 20 30值运行脚本,脚本将返回: for i in range(4): k1, k2, k3, k4 = input().split(" ") k2 = float(k2) k3 = float(k3) k4 = float(k4) score = (k

输入有4个值:string、int、int、int。 我想把k1的值设为key,把分数设为value。 当我尝试上述代码时,输出如下:

以下是有效的代码(对原始代码进行了非常小的修改)

如果使用
1 10 20 30
值运行脚本,脚本将返回:

for i in range(4):
    k1, k2, k3, k4 = input().split(" ")
    k2 = float(k2)
    k3 = float(k3)
    k4 = float(k4)
    score = (k2 + k3 + k4) / 3
    print({k1: score})
以下是有效的代码(对原始代码进行了非常小的修改)

如果使用
1 10 20 30
值运行脚本,脚本将返回:

for i in range(4):
    k1, k2, k3, k4 = input().split(" ")
    k2 = float(k2)
    k3 = float(k3)
    k4 = float(k4)
    score = (k2 + k3 + k4) / 3
    print({k1: score})

您首先需要初始化字典,然后可以使用
dictionary[key]=value

{'1': 20.0}
这将执行以下操作:

# Initialise a dictionary where we can store values to
a = {}

# How many times we will ask for values
n = int(input('number of values: '))

for i in range(n):
    k1,k2,k3,k4 = input('give input: ').split(' ')
    k2 = float(k2)
    k3 = float(k3)
    k4 = float(k4)
    score = (k2+k3+k4)/3
    # Store the score value to k1 key
    a[k1] = score

# Print the dictionary after the loop has been completed
print(a)

您首先需要初始化字典,然后可以使用
dictionary[key]=value

{'1': 20.0}
这将执行以下操作:

# Initialise a dictionary where we can store values to
a = {}

# How many times we will ask for values
n = int(input('number of values: '))

for i in range(n):
    k1,k2,k3,k4 = input('give input: ').split(' ')
    k2 = float(k2)
    k3 = float(k3)
    k4 = float(k4)
    score = (k2+k3+k4)/3
    # Store the score value to k1 key
    a[k1] = score

# Print the dictionary after the loop has been completed
print(a)

不确定你想要实现什么。a={k1,score}print(a)这不起作用吗?我相信你可能也漏掉了for-in块中的缩进。你能编辑并详细说明你的预期结果吗?这样你的意图就清楚了?@dassum我想要一本字典,它的键是k1,值是分数。按照你说的做,我将得到一本包含k1和分数的字典。我编辑了你的问题,并对你的缩进进行了修正。也把答案贴在下面。不确定你想达到什么目的。a={k1,score}print(a)这不起作用吗?我相信你可能也漏掉了for-in块中的缩进。你能编辑并详细说明你的预期结果吗?这样你的意图就清楚了?@dassum我想要一本字典,它的键是k1,值是分数。按照你说的做,我将得到一本包含k1和分数的字典。我编辑了你的问题,并对你的缩进进行了修正。也在下面贴了答案。实际上我的不好。甚至最后一行都在循环中。实际上我的不好。甚至最后一行都在循环中