gpt4 book ai didi

python - 有没有一种 Pythonic 的方法可以使这个逻辑更优雅?

转载 作者:行者123 更新时间:2023-11-28 19:51:34 25 4
gpt4 key购买 nike

我是 Python 的新手,我一直在使用它来完成简单的任务。我有一堆 CSV,需要以复杂的方式进行操作,但为了学习 Python,我将其分解为更小的任务。

现在,给定一个字符串列表,我想删除字符串中任何名称的用户定义标题前缀。任何包含名称的字符串将包含一个名称,有或没有标题前缀。我有以下内容,它有效,但感觉不必要地复杂。有没有更Pythonic的方法来做到这一点?谢谢!

# Return new list without title prefixes for strings in a list of strings.
def strip_titles(line, title_prefixes):
new_csv_line = []
for item in line:
for title_prefix in title_prefixes:
if item.startswith(title_prefix):
new_csv_line.append(item[len(title_prefix)+1:])
break
else:
if title_prefix == title_prefixes[len(title_prefixes)-1]:
new_csv_line.append(item)
else:
continue
return new_csv_line

if __name__ == "__main__":
test_csv_line = ['Mr. Richard Stallman', 'I like cake', 'Mrs. Margaret Thatcher', 'Jean-Claude Van Damme']
test_prefixes = ['Mr.', 'Ms.', 'Mrs.']
print strip_titles(test_csv_line, test_prefixes)

最佳答案

[re.sub(r'^(Mr|Ms|Mrs)\.\s+', '', s) for s in test_csv_line]

关于python - 有没有一种 Pythonic 的方法可以使这个逻辑更优雅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3783728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com