Python如何从字典数组中按国家筛选并生成排序格式化输出
问题描述
现有结构如下的字典数组:
data = [ { "fname" : "John", "lname" : "Doe", "country" : [ "England" ] }, { "fname" : "Jane", "lname" : "Smith", "country" : [ "Germany" ] }, { "fname" : "John", "lname" : "Foo", "country" : [ "England", "Germany" ] }, { "fname" : "Jane", "lname" : "Bar", "country" : [ "Germany" ] } ]
需要实现按国家筛选、人名按姓氏排序后输出,预期效果如下:
England: John Doe, John Foo Germany: Jane Bar, John Foo, Jane Smith
已编写的初步处理函数存在语法错误,且调用print(personInCountry(data))无法得到预期的逐行输出效果:
def personInCountry(data) newdic = {} for dic in data: for country in dic['country']: if not country in newdic: newdic[country] = [] newdic[country].append('{} {}'.format(dic['fname'], dic['lname'])) for k, v in newdic.items(): print('{}: {}'.format(k, ', '.join(sorted(v, key=lambda x: x.split( [-1]))))
修复方案
现有代码的核心问题如下:
- 语法错误:函数定义行末尾缺冒号、
split方法缺括号、循环打印行末尾缺闭合括号 - 函数无返回值:如果在函数内部直接打印,调用
print(函数)时会额外输出None - 缺少排序逻辑:未对国家输出顺序做控制,可能出现输出顺序不稳定的问题
修复后的完整代码如下:
def personInCountry(data): newdic = {} for dic in data: for country in dic['country']: if country not in newdic: newdic[country] = [] newdic[country].append(f"{dic['fname']} {dic['lname']}") # 按字母顺序排序国家,同时对每个国家下的人名按姓氏排序 res_lines = [] for country in sorted(newdic.keys()): sorted_names = sorted(newdic[country], key=lambda x: x.split()[-1]) res_lines.append(f"{country}: {', '.join(sorted_names)}") # 返回拼接好的带换行的字符串 return '\n'.join(res_lines) # 调用即可直接输出预期效果 print(personInCountry(data))
内容的提问来源于stack exchange,提问作者Anders Begtorp
相关产品推荐
相关产品推荐

