我有这个
>>> 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)), '-')
循环体在 0
和 len(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/