我有這個如何在任意位置插入元素到列表中?
>>> a = [1, 4, 7, 11, 17]
>>> print a
[1, 4, 7, 11, 17]
有什麼辦法增加4個字符 ' - ' 其他元素之間隨機才達到例如
['-', 1, '-', 4, 7, '-', '-', 11, 17]
我有這個如何在任意位置插入元素到列表中?
>>> a = [1, 4, 7, 11, 17]
>>> print 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]
非常感謝你 – rikovvv
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()會產生從你的列表索引範圍內的隨機整數。 就是這樣。
你可以使用迭代器和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]
雖然會混合順序,但不是隨便添加連字符。 –
好點,更新。 – AChampion
由於性能不是問題,以下是另一種解決您的問題(每@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]
這並沒有完全解決這個問題,因爲你不能保證'4'穿插'''''' – AChampion
感謝評論,@AChampion。 – boardrider
注意:由於第二個循環可以完成所有工作,因此您的第一個循環現在基本上是不必要的。而你的第一個循環將不會提供均勻的分佈,因爲它會略微偏向前面的''''。 – AChampion
使用'random.randint'隨機生成索引並將其插入。 –