DekGenius.com
PYTHON
how to sort list python
a_list = [3,2,1]
a_list.sort()
how to sort a list in python
l=[1,3,2,5]
l= sorted(l)
print(l)
#output=[1, 2, 3, 5]
#or reverse the order:
l=[1,3,2,5]
l= sorted(l,reverse=True)
print(l)
#output=[5, 3, 2, 1]
Sorting a list using a named function
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
def second_let(x):
lst= []
for wrd in x:
lst.append(wrd[1])
return lst
print(second_let(ex_lst))
print(sorted(second_let(ex_lst)))
sorted_by_second_let= sorted(ex_lst, key= second_let)
how to sort a list in python
old_list = [3,2,1]
old_list.sort()
python sort a list using defined order
>>> A = [[3,5],[1,3],[6,1]]
>>> B = [6,1,3]
>>> srt = {b: i for i, b in enumerate(B)}
>>> sorted(A, key=lambda x: srt[x[0]])
[[6, 1], [1, 3], [3, 5]]
python sort a list using defined order
>>> sorted(A, key = lambda i: B.index(i[0]))
[[6, 1], [1, 3], [3, 5]]
sort a list python
"""Sort in ascending and descending order"""
list_test = [2, 1, 5, 3, 4]
#ascending is by default for sort
#Time Complexity: O(nlogn)
list_test.sort()
#For descending order
#Time Complexity: O(nlogn)
list_test.sort(reverse=True)
#For user-define order
list_test.sort(key=..., reverse=...)
© 2022 Copyright:
DekGenius.com