如何使用带变量的字典

时间:2016-06-23 20:31:27

标签: python

我正在尝试创建一个python程序来自动排序我正在处理的作业。到目前为止,我已经设法创建了一本字典。 例如:

monday = ('1' : 'clean the counters')

并为每个人分配一个号码:

joe = random.randint(1,3)

但是当我尝试时:

print ("Today Joe has to do the", monday[joe]") 

它吐出了错误。

有更好的方法可以做到这一点,还是我错过了一些明显的东西?

3 个答案:

答案 0 :(得分:3)

您有一个额外的引号会导致错误。您还需要将分配给joe的整数转换为char / string,因为这是它存储在字典键中的方式。

更好的方法是将字典设为列表。在1 / 2表单中使用3charstring只是添加了不必要的查找级别。

例如:

Monday = ["clean the counters", "wash the floor", "take out the trash"]
joe = random.randint(0, 2)  # or joe = random.randint(0, Monday.length)
print("Today Joe has to do the", Monday[joe])`

答案 1 :(得分:1)

您的代码中存在一些错误。首先,您应该使用{}来定义字典,而不是(),例如:

monday = {1 : 'clean the counters'}

另外,您会注意到我从1开始引用,因为如果您的所有键都是字符串,则无法使用randint生成的整数键搜索字典。

最后,当你打印时,你可能想要:

print ("Today Joe has to " + monday[joe])

因为你拥有它的方式不会产生正常的句子。

答案 2 :(得分:0)

尝试对您的代码进行以下修改,它应该有效:

monday = {'1' : 'clean the counters', '2' : 'upload the files', '3' : 'pick up the garbage'}
joe = str(random.randint(1, 3))
print("Today joe has to do : " + monday[joe])
相关问题