2017-06-04 69 views
2

我有这个如何在任意位置插入元素到列表中?

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

有什么办法增加4个字符 ' - ' 其他元素之间随机才达到例如

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

使用'random.randint'随机生成索引并将其插入。 –

回答

6

你可以简单地做:

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] 
+0

非常感谢你 – rikovvv

1

Python有插入(指数值)列表方法,将做的伎俩。 你想要的是:

import random 

l = [1, 2, 3, 4] 
for x in range(0, 4): # this line will ensure 4 element insertion 
    l.insert(random.randrange(0, len(l)-1), '-') 

randrange()会产生从你的列表索引范围内的随机整数。 就是这样。

2

你可以使用迭代器和random.sample()随机交错'-' S:

In [1]: 
a = [1, 4, 7, 11, 17] 
pop = [iter(a)]*len(a) + [iter('-'*4)]*4 
[next(p) for p in random.sample(pop, k=len(pop))] 

Out[1]: 
['-', '-', 1, '-', 4, 7, 11, '-', 17] 
+1

虽然会混合顺序,但不是随便添加连字符。 –

+0

好点,更新。 – AChampion

0

由于性能不是问题,以下是另一种解决您的问题(每@AChampion评论修订):

from __future__ import print_function 

import random 

_max = 4 
in_list = [1, 4, 7, 11, 17] 
out_list = list() 

for d in in_list: 
    if _max: 
     if random.choice([True, False]): 
      out_list.append(d) 
     else: 
      out_list.extend(["-", d]) 
      _max -= 1 
    else: 
     out_list.append(d) 

# If not all 4 (-max) "-" have not been added, add the missing "-"s at random. 
for m in range(_max): 
    place = random.randrange(len(out_list)+1) 
    out_list.insert(place, "-") 

print(out_list) 

其中给出:

$ for i in {1..15}; do python /tmp/tmp.py; done 
[1, '-', 4, '-', '-', 7, 11, '-', 17] 
['-', 1, 4, '-', '-', 7, 11, '-', 17] 
['-', 1, 4, '-', 7, '-', 11, 17, '-'] 
[1, '-', 4, '-', '-', 7, '-', 11, 17] 
[1, '-', 4, '-', '-', 7, 11, '-', 17] 
['-', 1, 4, '-', 7, 11, '-', 17, '-'] 
['-', '-', 1, '-', 4, '-', 7, 11, 17] 
[1, 4, '-', 7, '-', '-', '-', 11, 17] 
['-', 1, 4, 7, '-', 11, '-', '-', 17] 
[1, 4, '-', '-', '-', 7, '-', 11, 17] 
['-', '-', 1, 4, 7, 11, '-', 17, '-'] 
['-', '-', 1, '-', 4, '-', 7, 11, 17] 
['-', 1, '-', 4, '-', 7, 11, '-', 17] 
[1, '-', 4, '-', 7, '-', 11, '-', 17] 
[1, '-', '-', 4, '-', 7, 11, '-', 17] 
+0

这并没有完全解决这个问题,因为你不能保证'4'穿插'''''' – AChampion

+0

感谢评论,@AChampion。 – boardrider

+0

注意:由于第二个循环可以完成所有工作,因此您的第一个循环现在基本上是不必要的。而你的第一个循环将不会提供均匀的分布,因为它会略微偏向前面的''''。 – AChampion