2016-04-30 88 views
3

如果我有这样的事情:如何随机替换字符串列表中的

L = ['-','-','-','-','-','-','-'] 

而且我们说,我想更换一定数量的字符串。我如何在列表中随机选择一个位置来替换其他位置?例如:

L = ['-','*','-','-','-','*','*'] 
+2

您是否尝试过什么了吗?也许从'import random'开始 –

回答

2

使用random.randrange

import random 

some_list=["-","-","-","-","-","-","-"] 

n=2 
for i in range(n): 
    some_list[random.randrange(0,len(some_list))]="*" 

非重复的解决方案:

import random 

some_list=["-","-","-","-","-","-","-"] 

n=8 
if n>len(some_list): 
    some_list=["*" for i in some_list] 
else: 
    for i in range(n): 
      position=random.randrange(0,len(some_list)) 
      while some_list[position]=="*": 
        position=random.randrange(0,len(some_list)) 
      some_list[position]="*" 

print(some_list) 
+0

如果'random.randrange(0,len(some_list))在两次调用中返回相同的值会怎么样? – Tonechas

+0

检查编辑的答案。 – Damian

1

使用random.choice

import random 

L = ['-','-','-','-','-','-','-'] 

while L.count('*') < 3: 
    pos = random.choice(range(len(L))) 
    L[pos] = '*' 

print(L) 
3

其实,你可以使用该模块random其功能randint,因为它遵循:

import random 

num_replacements = 3 
L = ['-','-','-','-','-','-','-'] 

idx = random.sample(range(len(L)), num_replacements) 

for i in idx: 
    L[i] = '*' 

欲了解更多信息,可以检查random模块文档位于:https://docs.python.org/3/library/random.html

编辑:现在使用random.sample抽样随机数,而不是使用random.randint,它可能在不同的迭代过程中产生相同的数字。

+2

对randint的单独调用可以生成相同的数字。使用'random.sample'可能会更好。 – ayhan

2
import random as r 

L = ['-','-','-','-','-','-','-'] 

def replaceit(L,char): 
    L[r.randint(0,len(L))] = char 
    return L 

newL = replaceit(L,'*') 
print newL 

只需用newL替换另一个随机字符即可。

0

假设ü要以 '' 来代替它:

尝试以下操作:

from random import * 

L = ['-','-','-','-','-','-','-'] 
r = randint(0,len(L)) 
L[r] = 'a' 

print L 
0

我有一个Java的背景下,一个新手到Python。 我会建议从该列表的第一个到最后一个索引生成一个随机数,并将新的字符串插入到新生成的索引中。

请参考this question在列表中的特定位置插入一个值。

0

这种非重复的解决方案依赖于random.shuffle()

>>> import random 
>>> L = ['-','-','-','-','-','-','-'] 
>>> n = 3 # number of strings to replace 
>>> indices = range(len(L)) 
>>> random.shuffle(indices) 
>>> for i in indices[:n]: 
...  L[i] = '*' 
... 
>>> L 
['-', '*', '*', '-', '*', '-', '-'] 
相关问题