for example I have a list
list = [['word1', 0.234], ['word2', 0.2], ['word3', 0.5], ['word4', 0,67]]
and I want to sort it by importance. Importance means how far is the value from 0.5. The list after sorting should be:
list = [['word2', 0.2], ['word1', 0.234], ['word4', 0.67], ['word3', 0,5]]
First I solved it by writing simple function based on bubble sorting but it's very slow.
def most_interesting_words(seznam):
"""sort list i.e. [['word', spamicity], ...], first tokens whose value was furthest from the neutral value of
for i in range(len(seznam)):
for j in range(len(seznam)):
#if dist_from_05(seznam[i][1]) > dist_from_05(seznam[j][1]):
if abs(0.5 - seznam[i][1]) > abs(0.5 - seznam[j][1]):
tmp = seznam[i]
seznam[i] = seznam[j]
seznam[j] = tmp
return seznam
How it can be solved with sorted() function?
To sort by distance from 0.5 you can use the following sorted() function:
my_list = [['word1', 0.234], ['word2', 0.2], ['word3', 0.5], ['word4', 0.67]]
print(sorted(my_list, key=lambda x: abs(0.5 - x[1]), reverse=True))
This would give you the following output:
[['word2', 0.2], ['word1', 0.234], ['word4', 0.67], ['word3', 0.5]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With