如何根据字符串中间的Age字段对Python列表元素进行排序
实现方案
方法1:正则匹配提取年龄(推荐,容错性高)
通过正则匹配固定的Age: 数字模式提取年龄值,不受字段顺序、分隔符微小变动影响:
import re list_names = ['Name: Mark - Age: 42 - Country: NL', 'Name: Katherine - Age: 23 - Country: NL', 'Name: Tom - Age: 31 - Country: NL'] # 按年龄升序排序 sorted_list = sorted(list_names, key=lambda item: int(re.search(r'Age: (\d+)', item).group(1))) print(sorted_list)
输出结果:
['Name: Katherine - Age: 23 - Country: NL', 'Name: Tom - Age: 31 - Country: NL', 'Name: Mark - Age: 42 - Country: NL']
如果需要按年龄降序排序,给sorted函数加reverse=True参数即可:
sorted_list_desc = sorted(list_names, key=lambda item: int(re.search(r'Age: (\d+)', item).group(1)), reverse=True)
方法2:字符串分割提取年龄(性能更高,要求格式完全固定)
如果你的字符串格式100%固定,都是以-作为字段分隔符,Age固定在第二个字段位置,可以直接分割字符串提取年龄:
list_names = ['Name: Mark - Age: 42 - Country: NL', 'Name: Katherine - Age: 23 - Country: NL', 'Name: Tom - Age: 31 - Country: NL'] # 按-拆分取第二个字段,再按:拆分取后半段转整数 sorted_list = sorted(list_names, key=lambda item: int(item.split(' - ')[1].split(': ')[1]))
内容的提问来源于stack exchange,提问作者Fish1996
相关产品推荐
相关产品推荐

