猿问

在一行中打印每个单词而不是 Python 中的字符?

考虑以下代码和输出


代码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:

http://img2.mukewang.com/60c9a6d40001be6800310631.jpg

我的意图是打印如下

我需要在哪里修改以按所需顺序打印?


梵蒂冈之花
浏览 195回答 2
2回答

MYYA

试试这个: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)

狐的传说

您希望在迭代之前拆分每个句子。这是因为,默认情况下,当您在 Python 中遍历字符串时,它将逐个字符地进行。通过调用split,您可以将字符串(按空格)拆分为单词列表。见下文。ls = ["one is one","two is two","three is three"]for sentence in ls:    for word in sentence.split():        print(word)oneis onetwoistwothreeisthree
随时随地看视频慕课网APP

相关分类

Python
我要回答