考慮以下代碼和輸出代碼1:ls = ["one is one","two is two","three is three"]for each_item in ls: print(each_item) 輸出 1:代碼2:ls = ["one is one","two is two","three is three"]for each_item in ls: for each_word in each_item: print(each_word)輸出 2:我的意圖是打印如下一是一二是二三是三我需要在哪里修改以按所需順序打?。?
2 回答

MYYA
TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
試試這個(gè):
ls = ["one is one","two is two","three is three"]
words = []
for each_item in ls:
words = each_item.split()
for word in words:
print(word)

狐的傳說(shuō)
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
您希望在迭代之前拆分每個(gè)句子。這是因?yàn)?,默認(rèn)情況下,當(dāng)您在 Python 中遍歷字符串時(shí),它將逐個(gè)字符地進(jìn)行。通過(guò)調(diào)用split,您可以將字符串(按空格)拆分為單詞列表。見(jiàn)下文。
ls = ["one is one","two is two","three is three"]
for sentence in ls:
for word in sentence.split():
print(word)
one
is
one
two
is
two
three
is
three
添加回答
舉報(bào)
0/150
提交
取消