I.sort(key=lambda x: (x[0],-x[1]))
suppose i have I=[[1,2],[1,4],[3,4]] then how will this lambda function will sort and can anyone explain me about how it will do step by step
What you're referring to is a complex search by multiple keys (1st AND 2nd keyes in your case):
Ascending by 1st key and
Descending by 2nd key.
This works for groups with ties.
What is happening can be illustrated by the following example:
I=[[1,2],[1,4],[3,4]]
func = lambda x: (x[0])
I.sort(key=func)
print(" Sort by 1st key:",I)
I=[[1,2],[1,4],[3,4]]
func = lambda x: (x[0], -x[1])
I.sort(key=func)
print("Sort by 1st AND 2nd key:",I)
Sort by 1st key: [[1, 2], [1, 4], [3, 4]]
Sort by 1st AND 2nd key: [[1, 4], [1, 2], [3, 4]]
Related
this is my first question in stackoverflow. Hope I'm clear.
I would like to transform the following list (sorted ascending by the first element of each item):
[[7, 4], [9, 4], [10, 1]]
into this(sorted descending by the second element of each item, then descending by the first element):
[[9, 4], [7, 4], [10, 1]]
I have tried the sort attribute with no success.
Any hint?
thks
To customize sorting behavior, you can provide the key keyword argument in sorted() or list.sort(). In OP's case, they key argument should be a function that takes in one item in the original list (i.e., a pair of numbers like [7, 4]) and then returns the pair of numbers reversed (i.e., [4, 7]). We need to reverse the sort because by default, the sorted() and list.sort() sort in from smallest to largest.
See more about sorting in python, and in particular the key functions, at https://docs.python.org/3/howto/sorting.html#key-functions.
original = [[7, 4], [9, 4], [10, 1]]
desired = [[9, 4], [7, 4], [10, 1]]
original_sorted = sorted(
original,
key=lambda pair: (pair[1], pair[0]), reverse=True)
original_sorted == desired # True
The lambda is a function. It is equivalent to the function below. We use a lambda here because it is compact and we do not need to refer to this function anywhere else.
def key_function(pair):
return pair[1], pair[0]
I have an array like this:
[[0, 46.0], [1, 83.0], [2, 111.0], [3, 18.0], [4, 37.0], [5, 55.0], [6, 0.0], [7, 9.0], [8, 9.0]]
I want to return the array where the second element is the highest. In this example: [2, 111]
How can I do that?
Until now I have tried numpy.amax(array, axis=0) and numpy.amax(array, axis=1). But they do not consider my condition, that I just want to consider the last element per array.
You could use max with a key argument:
result = max(arr, key = lambda x : x[1])
If you array is an numpy array, you can use np.argmax to get the index and slice:
a[np.argmax(a[:,1])]
# array([ 2., 111.])
If we want to compare on the basis of all indices of the list and not just the 1st element. If lists are identical, then sort by key. Also length of the list is not known in advance. In that case how to sort the keys. Below is the example:
{'A': [5, 0, 0], 'B': [0, 2, 3], 'C': [0, 3, 2]}
output:
[A, C, B]
Explanation: A is at 1st position because at 0th index 5 is highest and rest is 0. C is at 2nd position because 2nd 1st index of C is 3 compared to 1st index of B. As you can see we need to compare all positions to sort it and we don't know the array size before hand.
I tried below code:
countPos = {'A': [5, 0, 0], 'B': [0, 2, 3], 'C': [0, 3, 2]}
res = sorted(countPos.items(), key=lambda x: ((-x[1][i]) for i in range(3)))
Getting an error for above code. Could someone help me on this?
I think got a solution, which worked. This might be naive. I encourage gurus to rectify me.
r = sorted(countPos.items(), key=lambda x: x[0])
r = dict(r)
res = sorted(r.items(), key=lambda x: x[1], reverse=True)
So, first sorted based on keys and then I sorted based on values in reverse order.
I'd like to multiply the values of two columns per row...
from this:
to this:
I think this can be easily done by numpy or pandas. Here is a sample solution-
import pandas as pd
column = ['A','B','C']
dataframe = pd.DataFrame({"A":['a','b','c'],"B":[1,2,3],"C":[2,2,2]})
dataframe['D'] = dataframe['B']*dataframe['C']
print(dataframe)
The answer using pandas is perfectly ok, but to learn Python it is perhaps better to start using the built-in functions first. Here is the answer using lists
my_list = []
my_list.append([1, 2])
my_list.append([2, 2])
my_list.append([3, 2])
print(my_list)
sum_list = []
for element in my_list:
my_sum = element[0] + element[1]
sum_list.append(element + [my_sum])
print(sum_list)
Result
[[1, 2], [2, 2], [3, 2]]
[[1, 2, 3], [2, 2, 4], [3, 2, 5]]
Your exercise to add the first column!
I started learning python recently. I am trying to sort a list of lists similar to this. However, I'm not able to find the correct method to do so please help.
Consider the list [[1,4], [3,3], [3,2] ,[1,2], [1,3], [2,3], [1,5]]
now, using
def keyFunc(j):
return j[0]
job = sorted(job, key=keyFunc, reverse=True)
I got it down to [[all 3s], [all 2s], [all 1s]]
However, now I want to further sort it so that the lists with common keys are in the order of descending values of their keys.
i.e. [[3,3], [3,2], [2,3], [1,5], [1,4], [1,3], [1,2]]
How does one do that in python?
Why do you use a wrong key function when not using a key function already does what you want?
>>> sorted(job, reverse=True)
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
Or since you're assigning back to job anyway, you might want to do job.sort(reverse=True) instead of creating a new list.
You can change the keyFunc to be like
def keyFunc(j):
return j[0]*10+j[1]
or
ls = [[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
sorted(ls, key=lambda x: x[0]*10+x[1], reverse=True)
That will sort both of the numbers as you described.
I think you can just negate the sorting keys to sort descending twice:
>>> lst = [[1,4], [3,3], [3,2] ,[1,2], [1,3], [2,3], [1,5]]
>>> sorted(lst, key=lambda x: (-x[0], -x[1]))
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
(-x[0], -x[1]) will first sort by the first item, then if any ties occur sort on the second item, both in descending manner. We can make it descending by negating with the minus - sign.
But as suggested by #Heap Overflow, we don't need to do this because we can just pass reverse=True, and sorted() will naturally sort by the first item then the second in descending order. No need for a sorting key.
You can test this by running the following:
>>> sorted(lst, reverse=True)
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
>>> sorted(lst, key=lambda x: (x[0], x[1]), reverse=True)
[[3, 3], [3, 2], [2, 3], [1, 5], [1, 4], [1, 3], [1, 2]]
Which both give the same results.