And*_*ero 2 python split definition
这个问题与我的教育有关,我希望尽可能详细地提供给你的任何帮助 - 我不想复制粘贴代码并交给它.:)
任务很简单 - 创建一个名为writeshort(txt)的定义,取一串单词,只打印少于五个字符的单词.现在我已经完成了这个,但问题是特定sais的任务使用了一个定义.我在这里失败了.
没有定义的代码,有效:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
string = raw_input(”Write a few lines: ”)
txt = string.split()
result = []
for words in txt:
if len(words) > 4:
continue
result.append(words)
print ', '.join(result), ”have less than five letters!”
Run Code Online (Sandbox Code Playgroud)
现在看起来不错,打印没有任何令人讨厌的[''].但是这些定义呢?我已经尝试了几件事,这是最新的,但它只打印少于五个字母的第一个单词,并忽略其余的:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
string = raw_input(”Write a few lines: ”)
txt = string.split()
def writeshort(txt):
for txt in txt:
if len(txt) > 4: #Yes I know its a 4, but since it counts 0...
continue
return txt
print writeshort(txt), "have fewer letters than five!"
Run Code Online (Sandbox Code Playgroud)
我感谢任何帮助.感谢您花时间帮我学习Python!
是的,因为循环在writeshort遇到返回语句时会找到一个短字并立即返回.
如果您需要所有简短的单词writeshort,您需要先在列表中收集它们,然后最终返回列表.也许是这样的:
def writeshort(txt):
wordlist = []
for item in txt:
if len(item) > 4:
continue
wordlist += [item] # or wordlist.append(item) as in your first snippet
return wordlist
Run Code Online (Sandbox Code Playgroud)
整个功能可以用一行代码和更多pythonic代码代替:
[word for word in txt if len(word) <= 4]
Run Code Online (Sandbox Code Playgroud)
你写的for txt in txt:,这很奇怪.它将执行预期的操作(对原始中的每个项执行txt),但txt在每次迭代中将更改为列表中的项.