[英]Python: How can I make this function run multiple times at the same time
[英]Can I run the same function multiple times with the return value as the argument?
如果你給它一串顏色,代碼應該返回一個最終的顏色值,比如
此處顏色:GG、BG、RG、BR
變色:G、R、B、G
例如:'RGBG' 將返回 'B' 在這里,我寫了一個 function 來分配顏色標簽(分配)和另一個將提供分解的主字符串的函數。 當我根據主字符串的大小手動鍵入new_value = assign(main(again))時一切正常(RGBG -> BRR -> GR ->B; 4 次,但我在advance 因為 again 參數將有一個值開頭),但是當我再次使用 = assign(main(again))時返回一個空值,即使我在前面的行中給了參數一個值所以它不是“未定義的”參數”錯誤..我想。
我對此很陌生,如果您能以正確的方式指出我,我將不勝感激。 希望這條消息能讓你平安無事:)
def assign(xlist):
for x in range(len(xlist)):
if xlist[x] in ('BG', 'GB', 'RR'): xlist[x] = 'R'
elif xlist[x] in ('RG', 'GR', 'BB'): xlist[x] = 'B'
elif xlist[x] in ('BR'. 'RB', 'GG'): xlist[x] = 'G'
return ''.join(xlist)
def main(xrow):
nrow = []
for i in range(len(xrow)-1):
nrow.append(xrow[i] + xrow[i+1])
return(nrow)
def triangle(row):
global again
again = assign(main(row))
print(row)
print(again)
for k in range(len(row)-1):
again = assign(main(again))
return again
你可以這樣做:
s = 'RGBG'
dict_map = {
'BG':'R',
'GB':'R',
'RR':'R',
'RG':'B',
'GR':'B',
'BB':'B',
'BR':'G',
'RB':'G',
'GG':'G'
}
def process(s):
while len(s)!=1:
s = "".join([dict_map["".join(x)] for x in zip(s[:-1], s[1:])])
return s
print(process(s))
# B
讓我們分解一下:
您可以使用字典根據鍵將值轉換為其他值:
dict_map["BG"]
將返回“R”。 要使用字典,我們需要一個包含 2 個字符的元素列表。
我們使用以下命令創建該列表: [x for x in zip(s[:-1], s[1:])]
這將返回重疊元組的列表。 例如(“R”,“G”)
由於我們不能將此元組與字典一起使用,因此我們將它們"".join()
在一起,從而產生例如“RG”。
現在我們通過使用dict_map["RG"]
詢問字典哪些值用於該鍵,並在本例中得到“R”。
整個事情在這里完成: [dict_map["".join(x)] for x in zip(s[:-1], s[1:])]
現在我們又有了一個翻譯值列表。 我們再次將它"".join()
在一起得到一個新的字符串:“BRR”。 我們重復整個過程,直到字符串的長度為 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.