python - 在列表中选择一个随机对象
问题描述
所以我正在尝试制作一个程序,在列表中选择一个随机对象,然后引用该对象。
这是我的代码:
for hour in c.routine:
a = hour.hour
if hour.task == "idle":
if c.spouse:
if c.spouse[0].routine[a].task == "idle":
if hour.hour >= 6 and hour.hour <= 19:
x = random.choice(family_daytime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.spouse[0].routine[a].task = x
c.spouse[0].routine[y].task = x
if c.kids:
for k in range(len(c.kids)):
if c.kids[k].routine[a].task == "idle":
c.kids[k].routine[a].task = x
c.kids[k].routine[y].task = x
else:
x = random.choice(family_nighttime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.spouse[0].routine[a].task = x
c.spouse[0].routine[y].task = x
elif c.lover:
pick = random.choice(c.lover)
if c.lover[pick].routine[a].task == "idle":
c = random.randint(0,2)
if c == 1:
if hour.hour >= 6 and hour.hour <= 19:
x = random.choice(daytime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.lover[pick].routine[a].task = x
c.lover[pick].routine[y].task = x
else:
x = random.choice(nighttime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.lover[pick].routine[a].task = x
c.lover[pick].routine[y].task = x
当我运行此代码时,出现错误:
Traceback (most recent call last): File
"C:\Users\Patrick\Pictures\Python\Westhope\2.0\exe.py", line 9, in
<module>
routine_creation() File "C:\Users\Patrick\Pictures\Python\Westhope\2.0\world_init.py", line
721, in routine_creation
if c.lover[pick].routine[a].task == "idle": TypeError: object cannot be interpreted as an index
似乎是我尝试引用选择的方式,但我不确定为什么或如何解决它......
解决方案
如果您还需要索引,请使用random.randrange
from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])
推荐阅读
- javascript - 带有 ngx-translate 库 angular 4/5 下拉菜单的 html 中的 ng 模型
- php - 在 PHP (AWS/ResulData) 中访问多维关联数组时出错
- javascript - GraphQL 查询返回错误 .filter 不是函数
- javascript - 一个盒子不适合不同的屏幕分辨率
- web-scraping - 网页抓取产品详细信息,而不是 UIPath 中的列表/表格
- c# - Bot Framework - 等待用户在瀑布对话框中点击英雄卡动作
- .net - 为什么我不能处理表单?
- reactjs - 获取“schemeCategory20”未从“d3”导出以将 D3.js V.5.7 转换为 React JS 组件
- javascript - 如何将 JSON 数据显示到 HTML owl carousel?
- cpanel - 如果 cpanel 不支持共享主机的事件调度程序,解决方案是什么?