【发布时间】:2021-11-30 13:13:21
【问题描述】:
mydict = {}
while True:
num = int(input())
if num == 0 :
break
while num > 0:
inp = input().split(" ")
mylist = list(inp)
for i in range(0,len(mylist)):
if mylist[i] in mydict.values():
print(f"Yes, Value: '{mylist[i]}' exists in dictionary")
else:
print(f"No, Value: '{mylist[i]}' does not exists in dictionary")
mydict[mylist[i]] = 0
print(mydict)
for i in range(0,len(mylist)):
if i == 0 :
mydict[mylist[i]] += 3
if i == 1 :
mydict[mylist[i]] += 2
if i == 2 :
mydict[mylist[i]] += 1
print(mydict)
num-=1
这是我的代码,我不知道为什么它不明白字典中的某些值在添加后已经存在,我不希望他们将其更改为零
2
3 3 2 1
No, Value: '3' does not exists in dictionary
No, Value: '3' does not exists in dictionary
No, Value: '2' does not exists in dictionary
No, Value: '1' does not exists in dictionary
{'3': 0, '2': 0, '1': 0}
{'3': 5, '2': 1, '1': 0}
3 2 3 1
No, Value: '3' does not exists in dictionary
No, Value: '2' does not exists in dictionary
No, Value: '3' does not exists in dictionary
No, Value: '1' does not exists in dictionary
{'3': 0, '2': 0, '1': 0}
{'3': 4, '2': 2, '1': 0}
0
但我想要:
2
3 3 2 1
No, Value: '3' does not exists in dictionary
No, Value: '3' does not exists in dictionary
No, Value: '2' does not exists in dictionary
No, Value: '1' does not exists in dictionary
{'3': 0, '2': 0, '1': 0}
{'3': 5, '2': 2, '1': 0}
3 2 3 1
Yes, Value: '3' exists in dictionary
Yes, Value: '2' exists in dictionary
Yes, Value: '3' exists in dictionary
Yes, Value: '1' exists in dictionary
{'3': 5, '2': 2, '1': 0}
{'3': 9, '2': 4, '1': 0}
0
【问题讨论】:
-
不要使用
for i in range(len(some_list)):通过索引访问列表的值,使用for value in some_list: -
@Barmar 但随后代码进入设置
mydict[mylist[i]] = 0。我认为原始海报的 dict 键和值都混在一起了。 -
inp已经是列表,不需要list(inp) -
你能用预定义的输入创建一个更简单的例子吗?键和值之间有更清晰的区别,而不是它们都是小整数?这对我来说太混乱了。
-
为什么要在第二行写
3 does not exist in dictionary?上一行将其添加到字典中。
标签: python python-3.x dictionary key-value