Python 替换列表中的索引而不重复索引位置

Python 替换列表中的索引而不重复索引位置,python,list,indexing,Python,List,Indexing,所以我有一个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 retur

所以我有一个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

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]

问题是什么?@goks问题是随机的。randint(0,n_单元格)可以返回相同的值两次。
random.shuffle([0]*6+[1]*4)
@ReblochonMasque这真是太好了!你应该把它贴出来作为答案!您应该将其添加到您的中,作为替代选项,它实际上应该是
seq=[0]*6+[1]*4;随机。随机(seq);打印(seq)
因为random.shuffle返回None@OlivierMelan谢谢你!
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]