Help with python sorting?

hence im designed sort an inventory with that elements from the periodic technique.the listing looks something like this “Kr 83.80”, “La 138.9055”, “Li 6TH.941″…so the elements identify first after which the atomic bulk.what i have to do is sort the list according to the atomic muscle mass fast, so that this lightest feature comes first etc ..
I am a little a noob with regards to programming but i do think i understand the basics
many thanks!

Python’s sort() method can be given an extra argument referred to as ‘key’.That argument helps you control in what way each record item is given some sort of value that will be used as the basis for the sorting functioning.The argument is often a reference with a function this expects your list item just as one argument and also returns the particular sorting value that could be used for the item.

So, if anyone write the function which takes certainly one of your “name mass” strings just as one argument and also returns your floating-point price representing the particular mass, you can tell the sort() method to use this specific function to determine how that will sort your current list.The function would look something like this:

def getmass( piece ):
returning float( thing.split( ) ONE PARTICULAR )

and also the sort() name would mimic this:

elements = “Kr 83.80”, “La 138.9055”, “Li 6TH.941”

elements.sort( essential = getmass )

art print elements

In the event you call the sort() method with not a ‘key’ disagreement then you will need its own best speculate at how you can rank decorative accessories.When accents you want are strings, as they quite simply are here, it may sort these folks alphabetically.Look wonderful you wouldn’t get the result you need if you just called sort() with no arguments.

Leave a Reply