python中的Filter函数

2024-05-28 22:55:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张“姓名列表”。你知道吗

name_list=['Name:Bill,Age:28,Height:6.1', 'Name:Dona,Age:23,Height:6.1','Name:Bill,Age:22,Height:6.1', 'Name:Shelly,Age:24,Height:7'] 

1)我想用常用数据对列表排序。例如,输出应如下所示:

out=['Name:Bill,Age:28,Height:6.1', 'Name:Bill,Age:22,Height:6.1']

2)我想按最大年龄对列表排序。例如,如果我想检查谁有最大年龄输出应该是这样的。你知道吗

out=['Name:Bill,Age:28,Height:6.1']

这就是我到现在为止所做的:

name_list=['Name:Bill,Age:28,Height:6.1', 'Name:Dona,Age:23,Height:6.1','Name:Bill,Age:22,Height:6.1', 'Name:Shelly,Age:24,Height:7'] 


out = filter(lambda x:'Name:Bill' in x and 'Height:6.1' in x,list)

Tags: 数据namein列表age排序outlist
2条回答

我将使用collections.namedtuple组织数据:

In [41]: from collections import namedtuple
         person = namedtuple('person','name age height')

In [42]: persons=[person(*(i.split(':')[1] for i in n.split(','))) 
                                               for n in name_list]

In [43]: max(persons,key=lambda x:x.age)
Out[43]: person(name='Bill', age='28', height='6.1')

In [44]: max(persons,key=lambda x:x.height)
Out[44]: person(name='Shelly', age='24', height='7')

In [45]: max(persons,key=lambda x:x.height).name
Out[45]: 'Shelly'
In [46]: persons
Out[46]: 
[person(name='Bill', age='28', height='6.1'),
 person(name='Dona', age='23', height='6.1'),
 person(name='Bill', age='22', height='6.1'),
 person(name='Shelly', age='24', height='7')]

必须将列表转换为更易于处理的结构,例如:

people = [
    dict(x.split(':') for x in y.split(','))
    for y in name_list
]

这会给你一些类似于:

[{'Age': '28', 'Name': 'Bill', 'Height': '6.1'}, 
 {'Age': '23', 'Name': 'Dona', 'Height': '6.1'}, 
 {'Age': '22', 'Name': 'Bill', 'Height': '6.1'}, 
 {'Age': '24', 'Name': 'Shelly', 'Height': '7'}]

在这个列表中选择你需要的属性。例如,要找到最年长的人:

oldest = max(people, key=lambda x: x['Age'])

相关问题 更多 >

    热门问题