所以我有一个包含 10 个 0 的列表。
[0,0,0,0,0,0,0,0,0,0].
我必须在列表中插入 4 个随机 1。
[0,1,0,0,0,1,0,1,1,0].
如何插入没有重复索引的 1。
def init_positions(n_cells, n_veh):
lst = [0] * n_cells
for i in range(n_veh):
newL = random.randint(0, n_cells)
lst[newL] = 1
return lst
position = init_positions(10,4)
print(position)
最佳答案
您可以在范围
上使用random.sample
来选择n个不同索引。
import random
lst = [0] * 10
def insert_ones(n, lst):
for x in random.sample(range(len(lst)), n):
lst[x] = 1
insert_ones(4, lst) # [1, 0, 0, 1, 0, 0, 0, 1, 1, 0]
或者,您可以通过这种方式直接初始化列表,而不是改变它。
import random
def init_positions(n_cells, n_veh):
indices = set(random.sample(range(n_cells), n_veh))
return [1 if x in indices else 0 for x in range(n_cells)]
init_positions(10, 4) # [0, 1, 1, 1, 0, 0, 0, 0, 0, 1]
关于python - 替换列表中的索引而不重复索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403041/