如果我有这样的话:
L = ['-','-','-','-','-','-','-']
让我们说我想替换一定数量的这些字符串。如何随机选择列表中的位置以替换其他内容?例如:
L = ['-','*','-','-','-','*','*']
答案 0 :(得分: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
,这可能会在不同的迭代期间生成相同的数字。
答案 1 :(得分: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调用replaceit来替换另一个随机字符。
答案 2 :(得分: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)
答案 3 :(得分:1)
使用random.choice
import random
L = ['-','-','-','-','-','-','-']
while L.count('*') < 3:
pos = random.choice(range(len(L)))
L[pos] = '*'
print(L)
答案 4 :(得分:0)
假设你想用'a'替换它:
尝试以下方法:
from random import *
L = ['-','-','-','-','-','-','-']
r = randint(0,len(L))
L[r] = 'a'
print L
答案 5 :(得分:0)
我有一个Java背景,一个python的新手。 我建议从该列表的第一个到最后一个索引生成一个随机数,并将新字符串插入到新生成的索引中。
请参阅this question以在列表中的特定位置插入值。
答案 6 :(得分: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
['-', '*', '*', '-', '*', '-', '-']