python:字典的正确使用
我尝试创建一个函数,它生成随机的int值,在值出现两次之后,函数应该返回所有生成的int值的数目。 我得用字典 这是我目前的代码:python:字典的正确使用,python,dictionary,Python,Dictionary,我尝试创建一个函数,它生成随机的int值,在值出现两次之后,函数应该返回所有生成的int值的数目。 我得用字典 这是我目前的代码: def repeat(a,b): dict={} d=b-a+2 for c in range(1,d): dict['c']=random.randint(a,b) for f in dict: if dict['f']==dict['c']: retu
def repeat(a,b):
dict={}
d=b-a+2
for c in range(1,d):
dict['c']=random.randint(a,b)
for f in dict:
if dict['f']==dict['c']:
return c
第一个问题:它不起作用
>>> repeat(1,5)
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
repeat(1,5)
File "<pyshell#143>", line 7, in repeat
if dict['f']==dict['c']:
KeyError: 'f'
>>重复(1,5)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
重复(1,5)
文件“”,第7行,重复
如果dict['f']==dict['c']:
键错误:“f”
第二个问题:如果dict['f']==dict['c']:
在第一步中应为true,因为两个值相同
我找不到一种聪明的方法来比较所有的值,而不比较一个键本身
对不起,我的英语不好,有点生疏了,谢谢你抽出时间。将变量名括在引号中会使它们成为字符串-Python正在查找字母f的键,而不是
f
变量中带整数的键
只需正常使用该变量,它就会按照您的预期工作:
def repeat(a, b):
stored = {}
d = b - a + 2
for c in range(1, d):
stored[c] = random.randint(a, b)
for f in stored:
if stored[f] == stored[c]:
return c
还请注意,命名变量
dict
,是在隐藏内置函数dict()
——因此最好使用另一个名称。这并不是您问题的答案@厕所用品告诉了你这个问题。但我不能把代码放在评论中,所以我把它作为一个答案发布
您的代码使用了奇怪的变量名,这使得代码更难理解。我建议您使用变量名来帮助读者理解程序
我已经更改了变量名并添加了注释。我还输入了一个“docstring”,但我并不真正理解这个函数,所以我没有真正编写文档消息
def repeat(a,b): # short names are okay for a,b as they are just two numbers
"""
This is the "doc string". You should put in here a short summary of what the function
does. I won't write one because I don't understand what you are trying to do.
"""
# do not use built-in names from Python as variable names! So don't use "dict"
# I often use "d" as a short name for a dictionary if there is only one dictionary.
# However, I like @Lattyware's name "stored" so I will use it as well.
stored={}
# You only used "d" once, and it's the upper bound of a range; might as well just
# put the upper bound inside the call to range(). If the calculation was really long
# and difficult I might still use the variable, but this calculation is simple.
# I guess you can use "c" in the loop, but usually I use "n" for number if the loop
# is making a series of numbers to use. If it is making a series of indexes I use "i".
for n in range(1,b-a+2):
stored[n]=random.randint(a,b)
# Any for loop that loops over a dictionary is looping over the keys.
for key in stored:
# I don't understand what you are trying to do. This loop will always terminate
# the first time through (when n == 1). The line above this for loop assigns
# a value to stored[n], and n will be equal to 1 on the first loop; then this
# test will trivially succeed.
if stored[key] == stored[n]:
return n
没有什么东西是你从来没有分配过的f'指的是文字字符串f,而不是变量/迭代器。通常它可以工作:)非常感谢!工作代码:def repeat(a,b):dici={}d=b-a+2,对于范围(1,d)中的c:dici[c]=random.randint(a,b)对于dici中的f:if c=f和dici[f]==dici[c]:返回c