Hi,各位大神好,小弟初學Python,這段程式碼是照著書打的思考後有一段還是不太懂...所以上來邦幫忙技術版詢問
-------------------------以下程式碼-------------------------
start1 = ["fee" ,"fie" ,"foe"]
rhymes = [
("flop","get a mop"),
("fope","turn the rope"),
("fa","get your ma"),
("fudge","call the judge"),
("fat","pet the cat"),
("fog","walk the dog"),
("fun","say we're done")
]
start2 = "Someone better"
start1_caps = " ".join([word.capitalize() + "!" for word in start1]) #這段不太懂
for first, second in rhymes:
print(f"{start1_caps}{first.capitalize()}!")
print(f"{start2}{second}.")
-------------------------分隔線-------------------------
start1_caps = " ".join([word.capitalize() + "!" for word in start1])
print(start1_caps)
印出結果是:
Fee! Fie! Foe!
這段似乎是用很簡易(一行程式碼就可以完成一個迴圈)的方式打出來的,雖然很COOL看起來也很厲害!但我還在對這種寫法要解讀還有點吃力的階段QQ
參考看看
start1 = ["fee" ,"fie" ,"foe"]
print(start1)
start1_caps = []
for word in start1:
start1_caps.append(word.capitalize()+"!")
print(start1_caps)
print(" ".join(start1_caps))
我簡單解讀如下,再請補充
跑 for 迴圈
for word in start1
依序得到 start1 的 3 個值
start1 = ["fee" ,"fie" ,"foe"]
fee
fie
foe
字首大寫+!
word.capitalize() + "!"
Fee!
Fie!
Foe!
以空格(" ")組合在一起
" ".join()
Fee! Fie! Foe!
==補充回應的問題
2.但是如果換這種方法(想直接新增到start1)就無法新增驚嘆號到word裡面,應該說在提取word的時候就已經發現他沒有新增"!"了
start1 = ["fee" ,"fie" ,"foe"]
for word in start1:
word.capitalize() + "!"
print(word)
a = word.capitalize() + "!"
print(a)
主要在於 word 是取 start1,因此 print(word) 會印出
fee
fie
foe
轉化後的 word 值要記得再給一個變數,如下為 a
不然 word 還是 word
a = word.capitalize() + "!"
print(a)
Fee!
Fie!
Foe!
3.這方法更慘,直接無限驚嘆號給你看...
start1 = ["fee" ,"fie" ,"foe"]
for word in start1:
start1.append(word.capitalize() + "!")
# print(word)
# print(" ".join(start1))
print(start1)
因為 word 是從 start1 來
但你迴圈內卻一直增加內容(append)到 start1
所以愈跑愈長
print(start1)
['fee', 'fie', 'foe', 'Fee!']
['fee', 'fie', 'foe', 'Fee!', 'Fie!']
['fee', 'fie', 'foe', 'Fee!', 'Fie!', 'Foe!']
['fee', 'fie', 'foe', 'Fee!', 'Fie!', 'Foe!', 'Fee!!']
['fee', 'fie', 'foe', 'Fee!', 'Fie!', 'Foe!', 'Fee!!', 'Fie!!']
['fee', 'fie', 'foe', 'Fee!', 'Fie!', 'Foe!', 'Fee!!', 'Fie!!', 'Foe!!']
...
...
1.發現(新增進去start1_cap的方法),可以出現驚嘆號
start1 = ["fee" ,"fie" ,"foe"]
start1_cap = []
for word in start1:
start1_cap.append(word.capitalize() + "!")
print(start1_cap)
2.但是如果換這種方法(想直接新增到start1)就無法新增驚嘆號到word裡面,應該說在提取word的時候就已經發現他沒有新增"!"了
start1 = ["fee" ,"fie" ,"foe"]
for word in start1:
word.capitalize() + "!"
print(word)
print(" ".join(start1))
3.這方法更慘,直接無限驚嘆號給你看...
start1 = ["fee" ,"fie" ,"foe"]
for word in start1:
start1.append(word.capitalize() + "!")
print(word)
print(" ".join(start1))
第一個沒什麼問題~
第二個沒有加"!"我能理解,不過為什麼連轉大寫都沒有@@?
第三個無限迴圈透過debug模式已經知道為什麼會無限迴圈了,
start1會回傳到word加驚嘆號,加入後start1 list後面會直接新增驚嘆號的值,word抓不完又一直新增驚嘆號,所以就形成無限迴圈
a981406015
更新在原本的回覆裡
可以再看看
(已補上
了解了~感謝你的熱心回答,最佳解答絕對獻給你了
for word in start1:
a = word.capitalize() + "!" #這邊給它一個變數就可以了
print(a)