【发布时间】:2016-02-27 19:38:52
【问题描述】:
我想创建一个列表并用 15 个零填充它,然后我想将列表的 5 个随机点中的 0 更改为 1,所以它有 10 个零和 5 个,这是我尝试过的
import random, time
dasos = []
for i in range(1, 16):
dasos.append(0)
for k in range(1, 6):
dasos[random.randint(0, 15)] = 1
有时我会得到 0 到 5 个,但我想要 5 个, 如果我添加:
print(dasos)
...查看我的清单:
IndexError: list assignment index out of range
【问题讨论】:
-
或许你可以使用random.sample。
-
使用
randrange(0, 15)或randint(0, 14) -
正如@Gassa 所说,
random.sample(range(15), 5)将为您提供 0 到 14 之间的 5 个唯一数字。 -
另一种方法是首先将所有可能的索引保存在循环之外(例如
canditates = range(15)),用random.shuffle(candidates)打乱这个列表,然后使用前5个数字作为你的索引。
标签: list python-3.x random