1

我遇到了这个问题,我应该编写一个程序来吃几个单词(用逗号分隔)并用这些单词吐出一个干净的列表。我无法解决我的问题。有任何想法吗?

def wordlist(word):
    return word.split(',')    

def main ():    
    sentence = input("write a few words and seperate them with , ")
    splitsentence = wordlist(sentence)
    for item in splitsentence:
        print(item)

main()
4

4 回答 4

2

您每次都在打印列表,而不是您正在迭代的特定项目:

而不是print(splitsetnence),你需要print(item)

def main():
    sentence = input("write a few words and separate them with ,")
    splitsentence = wordlist(sentence)
    for item in splitsentence:
        print (item)

另外,请注意缩进。原始帖子中的代码看起来没有正确缩进。

于 2013-01-27T17:16:53.310 回答
1

用 raw_input() 替换 input()。

于 2013-01-27T17:16:39.510 回答
1

您的缩进已关闭,您应该使用它raw_input来获取字符串:

def wordlist(word):
    return word.split(',')


def main():
         sentence = raw_input("write a few words and seperate them with , ")
         splitsentence = wordlist(sentence)
         for item in splitsentence:
             print(item)
main()

此外,对于这样一个小任务,您可以删除该wordlist(word)功能:

def main():
         sentence = raw_input("write a few words and seperate them with , ")
         splitsentence = wordlist.split(')
         for item in splitsentence:
             print(item)
main()
于 2013-01-27T17:18:18.003 回答
1

使用raw_input代替input和替换print(splitsentence)print(item)

请记住,缩进是 Python 对语句进行分组的方式,就像 C 或 Java 使用{}

这是我的代码版本:

sentence = raw_input("write a few words and seperate them with , ")
splitsentence = sentence.split(',')
for item in splitsentence:
    print item

此代码不需要def main()或其他行。

于 2013-01-27T17:48:23.020 回答