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

Kee*_*som 2 python indexing list

所以我有一个10 0的列表.

[0,0,0,0,0,0,0,0,0,0].
Run Code Online (Sandbox Code Playgroud)

我必须在列表中插入4个随机1.

[0,1,0,0,0,1,0,1,1,0].
Run Code Online (Sandbox Code Playgroud)

如何在没有重复索引的情况下插入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)
Run Code Online (Sandbox Code Playgroud)

Oli*_*çon 5

您可以使用random.samplea range来选择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]
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过这种方式直接初始化列表,而不是改变它.

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]
Run Code Online (Sandbox Code Playgroud)

  • `random.shuffle([0]*6 + [1]*4)` (3认同)
  • 它应该是`seq = [0]*6 + [1]*4; random.shuffle(seq); print(seq)`因为random.shuffle返回None (2认同)