2013-01-15 65 views
0

我有1個列表「name_list」。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)我想用Max排序列表。年齡。例如,如果我想查看誰的最大年齡輸出應該是這樣的。

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) 
+0

什麼'屬性'包含在你的'普通數據'? –

+0

用戶輸入你想輸出爲':'姓名:比爾,年齡:28,身高:6.1','姓名:比爾,年齡:22歲,身高:6.1''? –

回答

0

我會用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')] 
1

您必須將列表轉換爲更易於結構處理,例如:

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'])