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

标签 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
    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/

相关文章:

python - C 到 Python 字谜

python - 无法让验证码出现

python:从PNG转换为JPG而不使用PIL将文件保存到磁盘

参数为列表的 MySQL 存储过程

java - 获取列表中出现多个的值?

c++ - 索引和更复杂的方法

python - 如何在 Python 中实现 Tic Tac Toe AI 的搜索算法?

Python比较两个字符串列表的相似性

python - Dicts 比较列表以在列表之间进行匹配并检测 Python 中的值变化

python - Pandas:获取重复的索引