Answers for "python sort by first element"

3

sort list of lists by first element

>>> lis = [[1,4,7],[3,6,9],[2,59,8]]
>>> sorted(lis, key=lambda x: x[0])
[[1, 4, 7], [2, 59, 8], [3, 6, 9]]
Posted by: Guest on October-25-2020
2

sort tuple by first element python

a = [(5,8), (3,4), (9,7)]

#sort by first element in tuple
result = sorted(a, key=lambda tup: tup[0])

#OR to do inplace sort:

a.sorted(key = lambda tup: tup[0])

# output
[(3, 4), (5, 8), (9, 7)]
Posted by: Guest on April-30-2020
5

python sort a list of lists by first element

# Basic syntax:
your_list.sort()

# Example usage:
your_list = [42, 17, 23, 111]
your_list.sort()
print(your_list)
--> [17, 23, 42, 111]

# If you have a list of numbers that are of type string, you can do the
# following to sort them numerically without first converting to type 
# int. E.g.:
your_list = ['42', '17', '23', '111']
your_list.sort(key=int)
print(your_list)
--> ['17', '23', '42', '111']

# If you want to sort a list of strings in place based on a number 
# that is consistently located at some position in the strings, use
# a lambda function. E.g.:
your_list =['cmd1','cmd10', 'cmd111', 'cmd50', 'cmd99']
your_list.sort(key=lambda x: int(x[3:]))
print(your_list)
--> ['cmd1', 'cmd10', 'cmd50', 'cmd99', 'cmd111']

# If you don't want to sort the list in place, used sorted. E.g.:
your_list = [42, 17, 23, 111]
your_list_sorted = sorted(your_list)
print(your_list_sorted)
--> [17, 23, 42, 111]
Posted by: Guest on September-28-2020

Code answers related to "python sort by first element"

Python Answers by Framework

Browse Popular Code Answers by Language