简体   繁体   English

python中的过滤功能

[英]Filter function in python

I am having 1 list "name_list". 我有1个列表“ name_list”。

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) I want to sort the list with common datas. 1)我想用常见数据对列表进行排序。 For example the output should come like this: 例如,输出应如下所示:

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

2) I want to sort the list with Max. 2)我想用最大排序列表。 Age. 年龄。 For example If I want to check out who is having max age output should come like this. 例如,如果我想查看谁拥有最大年龄输出,应该这样。

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

This is what I have done till now: 这是我到目前为止所做的:

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)

You have to convert the list to a structure that is easier to process, for example: 您必须将列表转换为更易于处理的结构,例如:

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

This gives you something like: 这给您类似:

[{'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'}]

Iterate over this list and pick whatever attributes you need. 遍历此列表并选择所需的任何属性。 For example, to find the oldest person: 例如,要找到年龄最大的人:

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

I would organize the data using collections.namedtuple : 我将使用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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM