在Python中构建随机列表

4

我在这里的代码有点问题。我正在尝试建立一个程序,每天生成一个新的锻炼计划。它应该从同一组锻炼中挑选出来,并创建用户当天使用的新列表。当我运行程序时,它返回了一个重复4次的相同项目列表,而应该是4个不同项目的列表。虽然我对Python和编程很陌生,但我似乎无法找到解决方案。我非常感谢任何帮助或建议。如何从列表中获取4个随机项,将它们附加到新的列表中,并且没有重复的项?

import random

chest_day_heavy = [["benchpress"], ["incline benchpress"], ["DB benchpress"], ["inclince DB press"],["seated machine press"]]
def workout_generator(muscle_group):
  workout_otd = []
  random_generator = random.randint(0,len(muscle_group))
  while len(workout_otd) < 4:
    workout_otd.append(muscle_group[random_generator])
    for i in range(len(workout_otd)):
      if muscle_group[random_generator] == workout_otd[i]:
        continue
  return workout_otd

print(workout_generator(chest_day_heavy))

例如,我希望结果是这样的:[["倾斜哑铃推举"],["坐姿器械推举"],["卧推"],["哑铃卧推"]]。 不要有重复的项目。 但实际得到的可能是这样的:[["坐姿器械推举"],["坐姿器械推举"],["坐姿器械推举"],["坐姿器械推举"]] 我可能在仅仅一个月的自学后期望过高了,哈哈。
5个回答

0
random_generator = random.randint(0,len(muscle_group))

应该放在 while 循环内部:
....
while len(workout_otd) < 4:
    random_generator = random.randint(0,len(muscle_group))
    workout_otd.append(muscle_group[random_generator])
    ....

成功了!谢谢你!现在要想办法确保我没有重复的项目。非常感谢你的帮助! - Kyler Keeley

0

正如Gabriele所说,.choice()是一个很好的方法,或者你也可以使用

random.shuffle(lst)

然后打印前4个项目。


0

OP在使用random.randint时的问题是它只会固定在一个索引上(因此重复相同的单个项目)。

random模块带有一些出色的函数,例如shuffle(),可以像这样使用:

def workout_generator(muscle_group):
    r = [*muscle_group]  # shallow copy the input list
    random.shuffle(r)
    return r

0

这可能是最简单的方法:

import random

chest_day_heavy = [["benchpress"], ["incline benchpress"], ["DB benchpress"], ["inclince DB press"],["seated machine press"]]
workout_otd=[]
def workout_generator(workout_otd):
    workout_otd=chest_day_heavy.copy()
    random.shuffle(workout_otd)
    return workout_otd

workout_otd= workout_generator(workout_otd)
print(workout_otd)

使用函数random.shuffle()可以将所有项目随机排序。
要仅打印前4个元素,可以像这样操作:print(workout_otd[0:4])

1
这帮助我解决了所有的问题!我感谢每个人的帮助!我使用了random.shuffle(),像Leemosh说的那样打印了前4个项目,然后我找到了解决方案。我终于可以继续下一步了。非常感谢你们! - Kyler Keeley

0

您可以使用随机模块的其他功能大大减少您的代码量,

import random

chest_day_heavy = [["benchpress"], ["incline benchpress"],
                        ["DB benchpress"], ["inclince DB press"],
                        ["seated machine press"]]

def workout_generator(muscle_group, n_wk):
    random.shuffle(muscle_group)
    return muscle_group[:min(n_wk,len(muscle_group))]

print(workout_generator(chest_day_heavy, 4))

现在列表在原地随机重新排列,函数按请求返回其中的前N个元素,以实现灵活性,元素数量——训练例程——是函数参数列表的一部分。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接