我使用 Vk API 并希望简化代码。因为我可以有10个这样的条件,但我不想用这个填写所有的代码。有没有办法减少?
这是代码:
def safe_file(posts):
with open('test.csv', 'w', newline='', encoding='utf-8') as file:
title = csv.writer(file, delimiter=';')
title. writerow(['text', 'image', 'url'])
for post in posts:
try:
if post ['id']:
i = post ['id']
else:
i = 'pass'
if post ['text']:
text = post ['text']
else:
text = 'pass'
if post ['attachments'][0]['photo']['sizes'][-1]['url']:
img = post ['attachments'][0]['photo']['sizes'][-1]['url']
else:
img = 'pass'
except:
pass
img = 'pass'
title.writerow((text, i, img))
我需要简化这部分代码:
for post in posts:
try:
if post ['id']:
i = post ['id']
else:
i = 'pass'
if post ['text']:
text = post ['text']
else:
text = 'pass'
if post ['attachments'][0]['photo']['sizes'][-1]['url']:
img = post ['attachments'][0]['photo']['sizes'][-1]['url']
else:
img = 'pass'
except:
pass
img = 'pass'
我会建议一个默认选项,所以让我们称之为
您仍然可以解决此问题并提出更好的建议,例如,将“通过”替换为更具体的内容,以便更容易在代码中进一步过滤和处理它。例如,为此创建一个特殊对象。
对于初学者,您可以使用条件运算符
使用条件表达式写得更短:
之后,我将创建一个执行所有三个任务的函数:
在程序中,这些分配看起来像这样:
在我看来 - 非常紧凑和可见。
更正的代码: