我從一個關于在 python 中反轉字串的相關問題中找到了這段代碼,但有人可以用簡單的英語解釋它嗎?請注意,我對 python 還是個新手,昨天才學會了如何使用 while 回圈和函式:/所以我自己不能真正用語言表達,因為我的理解還沒有完全到位。
無論如何這里是代碼:
def reverse_string(string):
new_strings = []
index = len(string)
while index:
index -= 1
new_strings.append(string[index])
return ''.join(new_strings)
print(reverse_string('hello'))
uj5u.com熱心網友回復:
當然,通過了解它的作用,您可以計算出代碼。在while回圈中,該index值從字串的末尾開始計數到 ??0。在每一步中,它都會將該字符(再次從末尾開始)添加到它正在構建的串列的末尾。最后,它將串列組合成一個字串。
因此,給定 'abcd',將構建串列:
'abcd' #3 -> ['d']
'abcd' #2 -> ['d','c']
'abcd' #1 -> ['d','c','b']
'abcd' #0 -> ['d','c','b','a']
uj5u.com熱心網友回復:
基本上,使用該len方法獲取字串的長度。這將回傳一個整數值,表示該字串的長度。
然后他們使用這個字串的長度并在while回圈中有效地迭代到零。使用-=運算子。
每次迭代(意思是每次回圈),它都會從 length 中移除,直到它達到零。
因此,讓我們將其hello用作示例輸入并一起完成。
reverse_string('hello')是我們如何呼叫該方法,在print您的代碼陳述句中完成。
然后我們進入函式并執行以下步驟:
- 我們創建了一個名為 的新空陣列
new_strings。 - 我們找到
hello回傳 5的初始字串的長度。這意味著現在index等于 5。 - 我們創建了一個持續運行直到
index不再使用while(index):的 while 回圈 - 像這樣的 while 回圈將一個0值視為falsy并在達到此值時終止。因此,當index是0回圈將停止。 - 此回圈的第一行執行
index -= 1與寫入相同,index = index - 1因此通過我們 getindex = 5 - 1和 then now 的第一個回圈index等于4。 - 因為 Python 然后讓我們訪問
character字串 usingstring[index](并且因為它從 0 -> n 開始作業)執行hello[4]實際上會給我們字符o。 - 我們還將這個字符附加到陣列中,
new_strings這意味著當我們通過迭代達到零時,它將向后添加每個字符到這個陣列給我們['o', 'l', 'l', 'e', 'h'] - 由于索引現在為零,我們離開回圈并對
join陣列執行操作以再次創建一個字串。該命令''.join(new_strings)意味著我們希望加入之前沒有分隔符的陣列。如果我們這樣做了,'#'.join(new_strings)我們就會得到o#l#l#e#h而不是olleh.
我希望這個答案能讓你清楚一些。
uj5u.com熱心網友回復:
當然,這是非常簡單的程式。您應該在 python 中參考字串方法和字串索引以獲得清晰的想法。讓我詳細解釋一下。
print(reverse_string('hello')) //列印函式正在呼叫另一個函式reverse_string并傳遞引數“hello”。
def reverse_string(string) :// 引數“hello”存盤在reverse_string函式中的變數string中。
**new_strings = []** // created a new empty list
**index = len(string)** // len function returns the length of the argument
passed to the function. len("hello")=5 and assigned
to index. index=5.
while index: // while 回圈執行,直到條件為 false 。在這個例子中,當 index =0.in string 索引從 0 開始。例如。string[0]=h,string[1]=e,string[2]=l,string[3]=l,string[4]=o。
**index -= 1** //Note the last letter 'o' is in string[4] and the len
function returned 5 so we need to decrement index variable
to 4 so that it will pointing to string[4]=o
new_strings.append(string[index]) // 追加字串[4],即 o 等等...... return ''.join(new_strings)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367120.html
上一篇:Python根據條件獲取部分字串
下一篇:mips:在堆中存盤字串的功能
