首页 > 解决方案 > 在列表中选择一个随机对象

问题描述

所以我正在尝试制作一个程序,在列表中选择一个随机对象,然后引用该对象。

这是我的代码:

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

似乎是我尝试引用选择的方式,但我不确定为什么或如何解决它......

标签: python

解决方案


如果您还需要索引,请使用random.randrange

from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])

推荐阅读