如何将元素插入列表中的任意位置? [英] How to insert elements into the list at arbitrary positions?
本文介绍了如何将元素插入列表中的任意位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个
>>> a = [1, 4, 7, 11, 17]
有没有办法在其他元素之间随机添加4个字符'-'
,例如
Is there any way to add 4 characters '-'
randomly between the other elements to achieve, for example
['-', 1, '-', 4, 7, '-', '-', 11, 17]
推荐答案
您可以轻松地做到:
import random
for _ in range(4):
a.insert(random.randint(0, len(a)), '-')
循环主体在 0
和 len(a)
(含)之间的随机索引处插入'-'
.但是,由于插入到列表中的代码是 O(N)
,因此根据插入的数量和列表的长度,最好在性能上构造一个新列表:
The loop body inserts a '-'
at a random index between 0
and len(a)
(inclusive). However, since inserting into a list is O(N)
, you might be better off performance-wise constructing a new list depending on the number of inserts and the length of the list:
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]
这篇关于如何将元素插入列表中的任意位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文