为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梵蒂冈之花 2021-06-11 15:21:19
考虑以下代码和输出代码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)


查看完整回答
反对 回复 2021-06-16
?
狐的传说

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


查看完整回答
反对 回复 2021-06-16
  • 2 回答
  • 0 关注
  • 182 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信