How to sort a list of lists by a specific index of the inner list?
This is a job for itemgetter
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
It is also possible to use a lambda function here, however the lambda function is slower in this simple case
How to order a list of lists based on number of elements within the inner list? - python
You can sort by the len
of the [0]
element of each sublist.
>>> sorted(a, key=lambda i: len(i[0]), reverse=True)
[[[5, 4, 3, 2], [6, 7, 8, 9]], [[5, 6, 7, 1], [9, 0, 3, 4]], [[1, 2, 3], [1, 2, 7]], [[2, 2], [0, 4]]]
Sorting List of List by inner list's index in Java? (Java Equivalent of Python's 'sorted()')
Since Java 8 there is method List::sort
accepting a custom Comparator
which can be built using Comparator.comparing
.
So, the input list of lists may be concisely sorted as follows:
List<List<String>> data = Arrays.asList(
Arrays.asList("Kelly", "3.0"),
Arrays.asList("Mark", "1.0"),
Arrays.asList("Jeff", "2.0")
);
// sorting by index 1
data.sort(Comparator.comparing(x -> x.get(1)));
// [[Mark, 1.0], [Jeff, 2.0], [Kelly, 3.0]]
// sorting by index 1 in reverse order using Collections.reverseOrder
data.sort(Comparator.comparing(x -> x.get(1), Collections.reverseOrder()));
// [[Kelly, 3.0], [Jeff, 2.0], [Mark, 1.0]]
// sorting by index 0 in reverse order using Comparator.reversed()
// here type of object being compared needs to be specified
data.sort(Comparator.comparing((List<String> x) -> x.get(0)).reversed());
// [[Mark, 1.0], [Kelly, 3.0], [Jeff, 2.0]]
sort list of lists by specific index of inner list
Use a custom sort key, to convert the last element to an integer just when sorting:
sorted(l1, key=lambda l: int(l[2].rstrip(',')))
The key
is used to produce the value on which to sort, for each element in the list. So the lambda
function is called for each element, and the above code extracts the l[2]
value, converting it to an integer. The str.rstrip()
call removes the trailing comma first.
Demo:
>>> l1 = [['test', 'hello', '60,'], ['why', 'to', '500,'], ['my', 'choice', '20,']]
>>> sorted(l1, key=lambda l: int(l[2].rstrip(',')))
[['my', 'choice', '20,'], ['test', 'hello', '60,'], ['why', 'to', '500,']]
How to sort a list of lists based on length of inner list?
Using sort
or sorted
with custom key.
Ex:
data = [['A', '1234', 'X'],['B', '12', 'X'],['C', '12345', 'X'],['D', '123', 'X']]
data.sort(key=lambda x: len(x[1]), reverse=True)
or sorted
data = sorted(data, key=lambda x: len(x[1]), reverse=True)
print(data)
Python- Sorting a list of lists by multiple indices, where inner lists may include None
Use sorted on your multidimensional list
l = [
['2016', 'E', None, '68', '94'],
['2016', 'A', None, '91', '25'],
['2016', 'C', None, '74', '25'],
['2017', 'C', None, '55', '20'],
['2015', 'D', None, '20', '14'],
['2016', 'B', None, '66', '66'],
['2017', 'E', None, '29', '41'],
['2017', 'F', None, '61', '22'],
['2015', 'A', None, '17', '96']
]
print(sorted(l))
prints
[['2015', 'A', None, '17', '96'], ['2015', 'D', None, '20', '14'], ['2016', 'A', None, '91', '25'], ['2016', 'B', None, '66', '66'], ['2016', 'C', None, '74', '25'], ['2016', 'E', None, '68', '94'], ['2017', 'C', None, '55', '20'], ['2017', 'E', None, '29', '41'], ['2017', 'F', None, '61', '22']]
Which is the same as your required output
Sort list of lists based on max value at a specific index in Python without the use of prebuilt functions or methods
In your code sample, you define food_list
as a tuple
while mentioning a list of list. In order to use list function like remove, copy or append, you need to add brackets around your lists.
Firstly, your food_list
should be defined this way :
food_list = [
['banana', 10, 'f', 'yellow'],
['apple', 12, 'f', 'red'],
['pear', 60, 'f', 'green'],
['mango', 5, 'f', 'yellow'],
['lettuce', 3, 'v', 'green'],
['beans', 20, 'v', 'green'],
['red capsicum', 1, 'v', 'red'],
['corn', 20, 'v', 'yellow'],
]
Secondly you set up your minimum value before iterating over the list, you consider the 1st element of your list in order to start looking for a lower integer.
minValue = unsorted_food_list_copy[0]
Complete solution :
# initializing list
food_list = [
['banana', 10, 'f', 'yellow'],
['apple', 12, 'f', 'red'],
['pear', 60, 'f', 'green'],
['mango', 5, 'f', 'yellow'],
['lettuce', 3, 'v', 'green'],
['beans', 20, 'v', 'green'],
['red capsicum', 1, 'v', 'red'],
['corn', 20, 'v', 'yellow'],
]
unsorted_food_list_copy = food_list.copy()
sorted_food_list = []
for i in range(len(unsorted_food_list_copy)):
minValue = unsorted_food_list_copy[0]
for x in unsorted_food_list_copy:
if x[1] < minValue[1]:
minValue = x
sorted_food_list.append(minValue)
unsorted_food_list_copy.remove(minValue)
sorted_food_list_descending = sorted_food_list[::-1]
print(sorted_food_list_descending)
# Ouput
[['pear', 60, 'f', 'green'],
['corn', 20, 'v', 'yellow'],
['beans', 20, 'v', 'green'],
['apple', 12, 'f', 'red'],
['banana', 10, 'f', 'yellow'],
['mango', 5, 'f', 'yellow'],
['lettuce', 3, 'v', 'green'],
['red capsicum', 1, 'v', 'red']]
Related Topics
Permissionerror: [Errno 13] Permission Denied
Tensorflow:Attributeerror: 'Module' Object Has No Attribute 'Mul'
How to Convert a 16-Bit to an 8-Bit Image in Opencv
Python Sockets Multiple Messages on Same Connection
Python Data Frame How to Find the Local Maximum in a 2D Array
Django: Get Current User in Model Save
Efficiently Find Repeated Characters in a String
Python - Returning Nan When Trying to Predict With Keras
How to Randomly Partition a List into N Nearly Equal Parts
How to Embed Matplotlib Graph in Django Webpage
How to Find Duplicate Values in a List and Merge Them
Find Out the Percentage of Missing Values in Each Column in the Given Dataset
Python3: How to Print Out User Input String and Print It Out Separated by a Comma
Return the First Key in Dictionary - Python 3
Python Strip Hyphen from Block of String
How to Print Numbers in a List That Are Less Than a Variable. Python
How to Find Last Occurence Index Matching a Certain Value in a Pandas Series