python - 如何在任意位置插入元素到列表中?

标签 python list

我有这个

>>> a = [1, 4, 7, 11, 17]

有没有办法在其他元素之间随机添加4个字符'-'来实现,比如

['-', 1, '-', 4, 7, '-', '-', 11, 17]

最佳答案

你可以简单地做:

import random
for _ in range(4):
    a.insert(random.randint(0, len(a)), '-')

循环体在 0len(a)(含)之间的随机索引处插入一个 '-'。但是,由于插入列表是 O(N),因此根据插入次数和列表长度构建新列表在性能方面可能会更好:

it = iter(a)
indeces = list(range(len(a) + 4))
dash_indeces = set(random.sample(indeces, 4))  # four random indeces from the available slots
a = ['-' if i in dash_indeces else next(it) for i in indeces]

关于python - 如何在任意位置插入元素到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358853/

相关文章:

Python 3.7 : Inheriting list, 摘要被忽略

python - 如何在 Python 中检测无按键/无输入?

Python 3 整数地址

python - 使用 boto3 更改 s3 对象 CacheControl

python - 获取具有给定索引的 Python 列表的子列表?

python - 用于列表理解 Python 的多个条件语句

python - 如何在Python中使用群补?

python - 将列表内的整数转换为字符串,然后转换为 python 3.x 中的日期

python - 列表中要 float 的字符串

python - 在列表的列表中操作字符串