【问题标题】:How can I write statement in more intelligent and shorter way? Python如何以更智能和更短的方式编写语句? Python
【发布时间】:2023-02-17 21:24:21
【问题描述】:

我正在检查count。如果键B没有count,则显示777,否则显示实际的count。在这种情况下,没有count,所以我应该显示777

有什么方法可以更智能、更简短地编写这条if else语句吗?

更不用说 if len(list) ==0: 我不想要那个。

代码:

results = [{'A': [{'_id': {}, 'count': 256}], 'B': []}]

if not results[0]['B']:
    updated_events = 777
else:
    updated_events = results[0]['B'][0]['count']
    
print(updated_events)

【问题讨论】:

  • 您可以使用 if else 来定义变量:updated_events = 777 if not results[0]['B'] else results[0]['B'][0]['count']

标签: python python-3.x if-statement data-structures


【解决方案1】:

或许

results = [{'A': [{'_id': {}, 'count': 256}], 'B': []}]

updated_events = results[0]['B'][0].get('count') if results[0]['B'] else 777
            
print(updated_events)

【讨论】:

    猜你喜欢
    • 2010-11-22
    • 2015-03-06
    • 2012-11-26
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多