[Tutor] operations on lists

Ondřej Rusek rusek at gybon.cz
Sun Apr 17 06:09:31 EDT 2016


marcus lütolf píše v St 13. 04. 2016 v 21:41 +0200:
> Hello experts
> 
> I'am working exercise 5. of 'Practical Programming 2nd edition, .....using Python 3'  (operations on lists).
> The following code get's me wrong results:
> 
> >>> metals = [['beryllium', 4],['magnesium', 12], ['calcium', 20], ['strontium', 38], ['barium', 56], ['radium', 88]]
> >>> max(metals)
> ['strontium', 38]
> >>> min(metals)
> ['barium', 56]
> 
> It should return 
> ['radium', 88] and 
> ['beryllium', 4] respectively

> 
> What's wrong ?

You must tell to function max() or min() what do you want... list metals
has nested lists - use lambda function like key function for max(),
min(), that the key value for sorting is the second value in nested
lists:

max(iterable, key=function)

max(metals, key=lambda item_of_nested_list:item_of_nested_list[1])
min(metals, key=lambda item_of_nested_list:item_of_nested_list[1])

This is only one way of solution...

-- 
S pozdravem

--
-------------------------------------------------
Ing. Ondrej Rusek
GYmnazium BOzeny Nemcove, Hradec Kralove, Czech
rusek at gybon.cz, http://www.gybon.cz/~rusek
-------------------------------------------------



-- 
Tato zprava byla prohledana na vyskyt viru
a nebezpecneho obsahu antivirovym systemem
MailScanner a zda se byt cista.



More information about the Tutor mailing list