考虑以下代码和输出代码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贡献1868条经验 获得超4个赞
试试这个:
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)
狐的传说
TA贡献1804条经验 获得超3个赞
您希望在迭代之前拆分每个句子。这是因为,默认情况下,当您在 Python 中遍历字符串时,它将逐个字符地进行。通过调用split,您可以将字符串(按空格)拆分为单词列表。见下文。
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
添加回答
举报
0/150
提交
取消