N
N
nuclear_skillet210112016-02-24 21:13:04
Python
nuclear_skillet21011, 2016-02-24 21:13:04

How to sort a list of tuples in python in python?

after the work of dict.items() there is a list of tuples of the form

[("a", 2), ("b", 4), ("c", 5), ....]

you need to sort them like this:
sorted(array, key=lambda x: -x[1], x[0])

to find the highest value, tell me how to organize the lambda function correctly
(The task was this: find the largest occurrence of a substring in a string and submit this substring to the output,
maybe I'm wrong inventing such an "ugly bicycle", I will be glad for any suggestions)
everything crumbles with - SyntaxError: positional argument follows keyword argument
Trouble on line 30:

import string
latin_str2 = string.ascii_lowercase
latin_str_list = list(latin_str2)
print(latin_str_list)
print()
numbers = ("1","2","3","4","5","6","7" ,"8","9","0")
def check(text):
stroca = text.lower()
Lstr = list(stroca)
print(Lstr)
my_dict = {}
for value in Lstr:
if value in latin_str_list:
counts_0 = text.count(value)
my_dict[value] = counts_0
array = my_dict.items()
print(array)
answer = sorted( array, key = lambda x: x[-1]) # error
print('this is QA :',answer)
return(answer)

All the best!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeniy _, 2016-02-24
@nuclear_skillet21011

Need to get the substring that occurs most often in a string?

a = [("a", 2), ("c", 5), ("b", 6)]
max(a, key=lambda x: x[1])[0]
=> b

if you just sort by value (max -> min):
sorted(a, key=lambda x:x[1], reverse = True)

=> [('b', 6), ('c', 5), ('a', 2)]

A
angru, 2016-02-25
@angru

you have a lot of extra moves:

def get_max(text):
    count_map = {char:text.count(char) for char in set(text)}

    return max(count_map, key=lambda char: count_map[char])

no need to convert a string to a sheet, you can iterate over them just fine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question