0

I am having 1 list "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. 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. 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)
2
  • And what attributes are included in your common datas? Commented Jan 15, 2013 at 9:38
  • For what user input you want the output as : 'Name:Bill,Age:28,Height:6.1', 'Name:Bill,Age:22,Height:6.1' ? Commented Jan 15, 2013 at 9:51

2 Answers 2

1

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

I would organize the data using 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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.