给定一个单词列表,如何去除超过四个字符的单词?
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。比如说,我们可能希望在用户点击一个按钮时,程序才开始运行某段代码。这个过程就叫做“事件处理”。
事件处理的基本思路是:程序会一直在等待用户的操作,比如点击、输入等。当用户进行某个操作时,程序就会“捕捉”到这个事件,然后执行相应的代码。
为了实现这一点,我们通常需要定义一个“事件监听器”。这个监听器就像是一个守卫,专门负责监视特定的事件。一旦事件发生,监听器就会通知程序去执行预先设定好的代码。
举个简单的例子,想象一下你在一个网页上看到一个按钮,你点击了它。这个点击动作就是一个事件,而事件监听器就是负责监控这个按钮的“守卫”。当你点击按钮时,监听器会立刻反应,执行你希望程序做的事情,比如显示一条消息或改变页面的内容。
总之,事件处理让程序能够对用户的操作做出反应,从而实现更互动的体验。
def remove_long_words(words):
"""Given a list of words, remove any that are longer
than four letters and return a new, shorter list.
w = ['one', 'two', 'three', 'four', 'eighteen']
remove_long_words(w)
['one', 'two', 'four']
w = ['eighteen']
remove_long_words(w)
[]
w = ['one', 'two', 'four', 'six']
remove_long_words(w)
['one', 'two', 'four', 'six']
remove_long_words(['one']) == ['one']
True
"""
replace this line with your code
2 个回答
0
2
下面的内容使用了“列表推导式”的概念。你可以在这里了解更多信息:http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
我建议你看看这段代码,了解一下列表推导式,并试着弄明白里面发生了什么。
def remove_long_words(words):
"""(list) -> list
Return a list of words that are less than or equal to
the length 4.
>>> remove_long_words(['eighteen'])
[]
>>> remove_long_words(['one', 'two', 'four', 'six'])
['one', 'two', 'four', 'six']
>>> remove_long_words(['one']) == ['one']
True
>>> remove_long_words(['one', 'two', 'three', 'four', 'eighteen'])
['one', 'two', 'four']
"""
return [i for i in words if len(i) <= 4]