我是編程新手,正在學習使用 python 的入門課程。我正在嘗試實作一個函式,該函式將字串串列和一個字符作為引數并列印到螢屏上,其中包含給定字符的所有字串。如果串列為空,則函式回傳“串列為空”。所以它應該是這樣的:
鑒于:
wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')
回傳:
Absolute Sense Test
鑒于:
wordsWithChar([],'r')
回傳:
'List is Empty'
編輯:我嘗試了以下方法:
def wordsWithChar(lst,x):
for word in lst:
print(word,end=' ')
print()
if len(lst)<1:
print('List is empty')
def wordsWithChar(lst,x):
for word in lst:
print (word)
if x in word:
print(word)
def wordsWithChar(lst,x):
newlst=[]
for word in lst:
newlst.append(word)
print(newlst)
if len(lst)<1:
print('List is empty')
if x in word:
newlst.append(x)
print(newlst)
def wordsWithChar(lst,x):
newlst=[]
for word in lst:
if x in lst:
newlst.append(word)
return newlst
print(' ',join(lst))
newlst=wordsWithChar(lst,x)
if len(newlst)<1:
print('List is empty')
else:
print(newlst)
我已經用 for 回圈和 if/else 陳述句嘗試了我所知道的一切,但無法弄清楚這一點。預先感謝您的幫助。
編輯:雖然我感謝所有的幫助,但隨著每個解決方案的提出,IDLE 進入 wordsWithChar 測驗并停止。由于某種原因,它不回傳任何值。只是跳到一個新的輸入行。
uj5u.com熱心網友回復:
你幾乎成功了:
def wordsWithChar(lst,x):
for word in lst:
print (word)
if x in word:
print(word)
陳述句的縮進if使它在回圈之后運行。但你會希望它在回圈內運行:
def wordsWithChar(lst,x):
for word in lst:
if x in word:
print(word)
if __name__ == "__main__":
wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')
這不會顯示“未找到”訊息。一種更 Pythonic 的方法是首先使用串列推導創建包含 x 的單詞串列:
words_containing_x = [ w for w in lst if x in w ]
# words_containing_x = ['Absolute', 'Sense', 'Test']
分解:
words_containing_x =- 新名單[ w for w in lst ...]新串列都w在串列中 - 一個副本[... if x in w]但只有當這個詞w包含x
如果這有點令人困惑,以下將回傳包含length的所有單詞:lstx
len_of_words_containing_x = [ len(w) for w in lst if x in w ]
# len_of_words_containing_x = [8, 5, 4]
回到問題。可以測驗該串列:
def wordsWithChar(lst,x):
words_containing_x = [ w for w in lst if x in w ]
if words_containing_x:
print(words_containing_x)
else:
print("Oh noes!")
uj5u.com熱心網友回復:
我覺得嵌套的 for 回圈是你最好的選擇。我不想直接給你答案,特別是因為這是一門課程,但嘗試以此為起點
def words_with_character(lst, char):
new_lst = []
for word in lst:
for x in word:
注意char未使用。您應該能夠弄清楚它應該在哪里實施。祝你編碼好運!
嗯實際上你的解決方案非常接近。
def wordsWithChar(lst,x):
newlst=[]
for word in lst:
if x in lst:
newlst.append(word)
return newlst
會作業,但你的縮進都錯了。縮進在 Python 中非常重要。您永遠不會word在回圈中使用的附加組件
def wordsWithChar(lst,x):
newlst=[]
for word in lst:
if x in word: # word is the wrong variable to use here
newlst.append(word)
return newlst
uj5u.com熱心網友回復:
請注意,此實作是基本的,絕不是查找包含特定字符的單詞的唯一或理想方法。
另請注意,此實作僅查找完全匹配的字符。所以wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'s')和wordsWithChar(['Absolute','IDE','Summary','Sense','Test'],'S')(注意大寫和小寫的s)不是同一個問題
def wordsWithChar(words, char):
words_with_char = []
for word in words:
if char in word:
words_with_char.append(word)
if len(words_with_char)<1:
print('List is empty')
else:
print(' '.join(words_with_char))
words = ['Absolute','IDE','Summary','Sense','Test']
char = 's'
words_with_char = wordsWithChar(words, char)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414641.html
標籤:
