[英]Python - change text in string by random from a list
我想通過我列表中的每個字母寫一個循環 function go 稱為原始。
original = ['ABCD', 'DCBA', 'AAAA', 'AABB']
letters = ['A', 'B', 'C', 'D']
p = 1
for o in original: # loop through the original list
for i in range(0,len(o)): # loop through each letter in selected list
if random.randint(1,10) == p: #if this gives me the probability that is met
# I want to change the current letter on the current index to
# something else different from the letter list by random (maybe random.choice)
我是 python 的新手,請您給點建議。 我不想使用 class 或任何其他庫,但請隨機使用
在 python 中,您根本無法修改字符串。 您可以通過索引獲取字母,select 特定字符串,但不能修改它們。 要更改所述列表,您可以使用original.pop(o)
並使用original.append('AB" + random.choice(letters) + 'C'
在列表中添加所述編輯字符串,如您所說。更清楚:您使用list.append(element)
將元素添加到列表中,並使用list.pop(element)
從列表中刪除元素。同樣,您永遠不能在 python 中編輯字符串,您只能創建新字符串並存儲已編輯的舊字符串例如, new_string = old_string[:4]
,此特定代碼將存儲 old_string 中的所有字符,直到索引 4 到新字符串中。真的希望我有所幫助!
首先,零
for i in range(0, len(o))
是多余的。 你想給 random.choice 一個字母列表,其中包括字母中的所有內容減去當前字母。 我能想到的最快方法是使用一組:
newletters = list(set(letters).difference(o[i])
現在您有一個列表,其中包含“字母”中的所有字母,除了 o[i] 處的字母。
要分配字母(在從 random.choice 獲得它之后),請將您的“原始”單詞變成一個列表:
o_list = list(o)
並將其分配為
l = random.choice(newletters)
o_list[i] = l
new_word = "".join(o_list)
至於將新詞實際插入原件列表中,您必須知道舊詞的索引 - 我會使用 enumerate 來執行此操作:
original = ['ABCD', 'DCBA', 'AAAA', 'AABB']
letters = ['A', 'B', 'C', 'D']
p = 1
for index, o in enumerate(original): # loop through the original list
for i in range(len(o)): # loop through each letter in selected list
if random.randint(1,10) == p:
newletters = list(set(letters).difference(o[i])
o_list = list(o)
l = random.choice(newletters)
o_list[i] = l
new_word = "".join(o_list)
original[index] = new_word
假設您要更新原始
import random
original = ['ABCD', 'DCBA', 'AAAA', 'AABB']
letters = ['A', 'B', 'C', 'D']
p = 1
for i, o in enumerate(original):
new_letters = [] # updated letters for word o
for c in o:
if random.randint(1,10) == p:
t = letters[:] # copy of letters
t.remove(c) # remove letter from copy (so letters remains unchanged)
new_letters.append(random.choice(t)) # choice over remaining letters
else:
new_letters.append(c)
original[i] = ''.join(new_letters) # convert newsletters list to string
# and replace in original
print(original)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.