簡體   English   中英

Python - While 循環接受用戶輸入並在終止后打印列表

[英]Python - While loop to take user input and once terminated prints the list

下面是我的代碼

loop = 1
listInput = []
finalList = []

while True:
  print('Type "Done" to finish')
  listInput = input('\nEnter a word: ')
  if listInput == 'done':
      print(finalList)
      break
  else:
      finalList = listInput.split()
      loop += 1

我正在讓循環工作,但是當我終止 while 循環時,它只打印最后輸入的單詞,而不是整個列表。

請協助。 干杯。 Python Newbee

finalList = listInput.split()將 finalList 更新為 listInput.split()。
所以,如果你想將listInput.split()堆疊到 finalList,
使用finalList += listInput.split()而不是finalList += listInput.split()

這正是你告訴它要做的事情。 在每次迭代中,您都會銷毀finalList的先前值並將其替換為當前結果。 如果你想保留它們,那么你必須append新詞不是覆蓋,像這樣:

else:
    finalList.append(listInput.split())

我不完全確定您的總體目標可能是什么,因此我不會提出更多改進建議。 你沒有給出你的問題陳述,你的編碼實踐並不完全清楚; 這將隨着時間的推移而出現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM