Search code examples
pythonstandards

I have some lists, I have merge them but how can I the value in descending order and put it as STD?


My lists are shown:

['river: 0.3']
['spread: 0.04']
['idaho: 0.5']

I want to merge them together first then rank by the value in descending order and put it as standard output. Finally print a sentence, for example the highest value is 0.711, it will print:

"the largest value is idaho"

Here is my attempt but I failed when I wanna rank it:

u = ['river: 0.3']
v = ['spread: 0.04']
s = ['idaho: 0.5']
mergelist = u + v + s
ranklist = sorted(mergelist, key=lambda x: x[1], reverse=True)
for i in ranklist:
    print(' '.join(list(map(str, i))))
print("the largest value is" + ' ' + ranklist[0])

The desired standard output is:

idaho 0.5
river 0.3
spread 0.04
the largest value is idaho

Solution

  • This is one approach

    u = ['river: 0.3']
    v = ['spread: 0.04']
    s = ['idaho: 0.5']
    mergelist = u + v + s
    
    import operator
    
    d = {}
    for i in mergelist:
        val = i.split(":")
        d[val[0].strip()] = float(val[1].strip())
    
    print("the largest value is {}".format(max(d.items(), key=operator.itemgetter(1))[0]))
    

    Output:

    the largest value is Idaho
    
    • split string by :
    • Form dict from split values.
    • Use operator to get max value from your dict.

    As requested in comments

    for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True):
        print(k, v)
    

    Output:

    idaho 0.5
    river 0.3
    spread 0.04