python - 将列表附加到字典值时出现键错误
问题描述
我有以下代码:
import random
dic = {2:[],4:[]}
lis = []
# Create a random dataset of 10 lists
for number in range(0,10):
# Each list consists of 8 random numbers ...
lis.append(random.sample(range(0,9),8))
# ... followed by a 2 or 4, corresponding to dic keys
lis[-1].append(random.randint(2,4))
# Iterate through lis. Append sublists to dic values, using key per
# last item of sublist, 2 or 4. Strip the key itself.
for i in lis:
dic[i[-1]].append(i[:-1]) # <----- getting a key error here
# End result should be dic looking like this (shortened):
# dic = {2:[[1,2,5,0,8],[0,4,2,8,3]],4:[[6,2,3,6,2],[2,2,3,1,3]]}
如评论中所示,当我尝试将子列表附加到dic
. 想不通为什么。帮助?
解决方案
由于不熟悉您的问题域,我不明白这段代码背后的基本原理。但是,我已经通过添加打印调用来运行它以显示正在发生的事情(我向您推荐的一种有价值的调试技术),问题就在这里:
lis[-1].append(random.randint(2,4))
randint(2,4)
返回 2 到 4 之间的随机整数,包括 3。当后续代码达到 3 时,您会收到一个关键错误。相反,该行应该使用如下内容:
lis[-1].append(random.choice((2, 4)))
推荐阅读
- magento2 - Magento 2:重新分配源后需要重新保存所有产品
- c# - 如何使用 MassTransit 为 _error 队列中的消息设置生存时间?
- ruby-on-rails - nil:Nilclass 错误的未定义方法电子邮件
- javascript - 如何在 JS“setAttribute”中使用“onclick”运行函数?
- python - 如何在我的 pygame 敌人上实现随机方向变化?
- amazon-web-services - AWS SQS 的轮询策略
- tensorflow - what is the meaning of "None" in TensorFlow keras model?
- javascript - Lodash orderBy 不对数组进行排序
- jenkins - 在系统上找不到 jenkins.xml
- ruby - Ruby 习惯用法:无需嵌套方法即可安装 `acts_as` 行为的模式(如在 Paranoia gem 中)