使用zip处理多列表数据 编写Python函数查询有活跃病例的国家
问题解决代码
易读的循环实现(适合初学者理解)
def active_countries(latest): active_country_list = [] # 同步遍历各字段对应的所有行数据 for total, death, recovered, country in zip( latest['Total Cases'], latest['Total Deaths'], latest['Recovered'], latest['Country'] ): # 按规则判定是否存在活跃病例 if (total - death) > recovered: active_country_list.append(country) return active_country_list
简化的列表推导式实现
def active_countries(latest): return [ country for total, death, recovered, country in zip( latest['Total Cases'], latest['Total Deaths'], latest['Recovered'], latest['Country'] ) if (total - death) > recovered ]
原代码问题说明
- 函数定义的入参是
data,但代码全程调用全局变量latest,参数没有实际作用,传入其他数据集时会直接报错 - 没有遍历组合后的数值和国家序列,判断语句用到的
c、d变量未定义 - 冗余中间变量过多,无需额外生成多个临时列表,遍历和判断逻辑可以合并完成
内容的提问来源于stack exchange,提问作者SahiL
相关产品推荐
相关产品推荐

