我正在解決一個問題,它遍歷字串串列,取每個字串的第一個字母并將所有內容轉換為串列中所有單詞的縮寫。例如,
print(recAbbrev(['central','processing','unit']))
應該回來
'CPU'
這是我現在的代碼:
def recAbbrev(lst):
'return a single string with the first character of all the strings in a list combined and capitalized.'
if len(lst)==0:
print('')
return
if len(lst)>0:
if type(lst[0])==list:
recAbbrev(lst[0])
else:
acronym = ""
letter = ""
letter = letter lst[0][:1]
letter = letter.upper()
#lst.pop[0]
acronym = acronym letter
print(acronym)
recAbbrev(lst[1:])
我有兩個問題,我似乎無法理解這段代碼。首先,我希望我的基本情況在空串列的情況下回傳 '' 。相反,它回傳 None。我該如何解決這個問題?這是我的輸出:
Starting recAbbrev
None
C
P
U
這是一個簡單的問題,但我怎樣才能讓所有內容都保持在一條線上?似乎遞回試圖阻止我這樣做。
uj5u.com熱心網友回復:
您正在列印值并且不回傳任何內容。你必須修改你的功能:
def recAbbrev(lst):
'return a single string with the first character of all the strings in a list combined and capitalized.'
if len(lst)==0:
return ''
if len(lst)==1:
return lst[0][0].upper()
else:
return lst[0][0].upper() recAbbrev(lst[1:])
然后測驗一下:
lst = ['central','processing','unit']
recAbbrev(lst)
uj5u.com熱心網友回復:
一個更簡單的解決方案可以是以下,除非你必須使用遞回,因為這是一個家庭作業:
def recAbbrev(lst):
return "".join([w[0].upper() for w in lst])
lst = ['central','processing','unit']
print(recAbbrev(lst))
輸出:
CPU
如果串列為空,這也適用,在這種情況下,它回傳空字串。
uj5u.com熱心網友回復:
print\n在列印字串的末尾有一個默認字符(請參閱此處的檔案)。更改print(acronym)為print(acronym, end='')
您得到的是None因為您正在列印recAbbrev,它沒有回傳,因此默認為回傳None。打電話就行recAbbrev(['central','processing','unit'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348027.html
上一篇:無法解釋遞回
下一篇:按日期對多個字串進行排序
