用 python作答:Define a function get_title(movielist) that returns a new list of movies with (year) removed. movielist contains titles of movie as string and year is always written as 4 digits within parathesis at the end of the title. For example 'Transformers (2007)' Example get_title(['Transformers (2007)']) -> ['Transformers'] movies1 = ['Transformers (2007)', 'Star Trek (2009)', "Schindler's List (1993)", 'Ip Man (2008)', 'Casino Royale (2006)', 'Back to the Future (1985)', 'Moon (2009)'] get_title(movies1) -> ['Transformers', 'Star Trek', "Schindler's List", 'Ip Man', 'Casino Royale', 'Back to the Future', 'Moon']
时间: 2023-08-18 19:10:36 浏览: 41
以下是 Python 代码实现:
```python
import re
def get_title(movielist):
new_list = []
for movie in movielist:
title = re.sub(r'\s*\(\d{4}\)', '', movie)
new_list.append(title)
return new_list
```
这个函数首先定义了一个空列表 `new_list`,然后遍历每个电影的字符串。对于每个字符串,使用正则表达式 `r'\s*\(\d{4}\)'` 匹配电影名后面的四位数年份,使用 `re.sub()` 函数将年份替换为空字符串,得到电影名。最后将处理后的电影名添加到 `new_list` 中并返回即可。
你可以这样调用这个函数:
```python
movies1 = ['Transformers (2007)', 'Star Trek (2009)', "Schindler's List (1993)", 'Ip Man (2008)', 'Casino Royale (2006)', 'Back to the Future (1985)', 'Moon (2009)']
print(get_title(movies1))
# 输出:['Transformers', 'Star Trek', "Schindler's List", 'Ip Man', 'Casino Royale', 'Back to the Future', 'Moon']
```