我正在嘗試創建一個將單詞轉換為數字的函式,其中一個引數是“深度”,如果深度為 1,則該函式將知道“好的,我正在翻譯一個單詞”,如果深度為 2,則該函式將知道“現在我正在翻譯單詞串列”......等等
問題:
如果 X == Y,有一種形式可以添加“for”回圈?這是函式的當前形式:def translate(input_: Union[str, list], depth: int = 3):
if depth == 1: # Just one word
sum: int = 0
for char in input_:
sum = 17 * ord(char)
return sum
if depth == 2: # list of words
buffer: list = []
for word in input_: # for each word in list
sum: int = 0
for char in word: # the same as depth == 1
sum = 17 * ord(char)
buffer.append(sum)
if depth == 3: # list of lists of words
buffer: list = []
for lst in input_:
for word in lst: # the same as depth == 2
sum: int = 0
for char in word:
sum = 17 * ord(char)
一個偽代碼解決方案
在 Python 中存在一種形式來做到這一點?:
If depth > 2:
MAIN.ADDFORLOOP(for LIST in INPUT) <- We added the for loop if there's more than one list to translate
if depth > 1:
MAIN.ADDFORLOOP(for WORD in LIST) <- We added a for loop if there's more than one word
Here, if depth is 3 all for loops will be created, if depth is two, just two for loops will be created, etc
MAIN.LOADALLTHEFORLOOPS()
for char in word:
# The function goes here
uj5u.com熱心網友回復:
你甚至不需要depth解決你的問題。您可以檢查您的物件是否是串列,并使用這樣的遞回:
def translate(input_: Union[str, list]):
sum = 0
for i in input_:
if isinstance(i, list):
sum = translate(i)
else:
sum = 17 * ord(i)
return sum
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/394628.html
上一篇:有沒有辦法不重復?
