bdh*_*har 3 python string coding-style
我有一个list的dict连键['name','content','summary',...].所有值都是字符串.但有些价值观None.我需要删除所有的新生产线content,summary以及一些其他的按键.所以,我这样做:
...
...
for item in item_list:
name = item['name']
content = item['content']
if content is not None: content = content.replace('\n','')
summary = item['summary']
if summary is not None: summary = summary.replace('\n','')
...
...
...
...
Run Code Online (Sandbox Code Playgroud)
我有点觉得这个if x is not None: x = x.replace('\n','')成语不那么聪明或干净.是否有更"pythonic"或更好的方法呢?
谢谢.
代码对你来说很笨拙,但部分原因是因为你在重复自己.这个更好:
def remove_newlines(text):
if text is not None:
return text.replace('\n', '')
for item in item_list:
name = item['name']
content = remove_newlines(item['content'])
summary = remove_newlines(item['summary'])
Run Code Online (Sandbox Code Playgroud)
如果您要使用标记值(无),那么您将负担检查它们的负担.
你的问题有很多不同的答案,但它们似乎缺少这一点:当没有条目编码相同的信息时,不要在字典中使用sentinel值.
例如:
bibliography = [
{ 'name': 'bdhar', 'summary': 'questioner' },
{ 'name': 'msw', 'content': 'an answer' },
]
Run Code Online (Sandbox Code Playgroud)
然后你可以
for article in bibliography:
for key in article:
...
Run Code Online (Sandbox Code Playgroud)
然后你的循环很好地不知道给定文章中包含哪些键(如果有的话).
在阅读您的评论时,您声称自己正在从其他地方获取该词典.所以先清理它的垃圾值.这是很多更清楚有一个清洁步骤则是通过代码来进行他们的误解.
Python有一个三元运算符,因此一个选项是以更自然的单词顺序执行此操作:
content = content.replace('\n', '') if content is not None else None
Run Code Online (Sandbox Code Playgroud)
需要注意的是,如果""和None是你的情况当量(这似乎是这样),你可以缩短它只是if content作为非空字符串评估为True.
content = content.replace('\n', '') if content else None
Run Code Online (Sandbox Code Playgroud)
这也遵循Python的成语显式优于隐式.这表明有人遵循代码,该值可以None非常清楚.
值得注意的是,如果你重复这个操作,可能值得将它封装为一个函数.
Python中的另一个成语是请求宽恕,而不是许可.所以,你可以简单地使用try,并except在AttributeError后面,但是,这将成为在这种情况下很多更详细的,所以它可能是不值得的,尤其是在检查的成本是如此之小.
try:
content = content.replace('\n', '')
except AttributeError:
content = None
#pass #Also an option, but as mentioned above, explicit is generally clearer than implicit.
Run Code Online (Sandbox Code Playgroud)