Sorting a list of tuples with multiple conditions

2024/9/8 8:48:23

I am currently trying to sort the following list:

list_ = [(1, '0101'), (1, '1010'), (1, '101'), (2, '01'), (2, '010'), (2, '10')]

These are the steps I want to take in order to sort it:

  1. Sort the list by the value of the first element of the tuples
  2. Next, sort the list by the length of the second element of the tuples (not the value, the length!) AFTER step 1 finishes.
  3. Next, sort the list by the value of the second element of the tuples AFTER step 1 and step 2 finishes.

My attempt:

sorted_by_length = sorted(list_, key=len x:x[1])

However, I received a syntax error concerning the x after key= len. What is the right variable I should be using in this case?

The correct, sorted list should be:

sorted_by_length = [(1, '101'), (1, '0101'), (1, '1010'), (2, '01'), (2, '10'), (2, '010')]

Thank you for help.

Answer

The key function can return a tuple.

sorted_by_length = sorted(list_,key=lambda x: (x[0], len(x[1]), float(x[1])))

This works because tuples are sorted lexicographically: (the first element of the tuple is used for sorting first, then the second element is used for breaking ties, and then the third element is used for breaking any remaining ties.)

See the excellent HOWTO Sort for an explanation of this and other issues related to sorting.


In [1]: list_ = [(1, '0101'), (1, '1010'), (1, '101'), (2, '01'), (2, '010'), (2, '10')]In [2]: sorted_by_length = sorted(list_,key=lambda x: (x[0], len(x[1]), float(x[1])))...: 
In [3]: sorted_by_length
Out[3]: [(1, '101'), (1, '0101'), (1, '1010'), (2, '01'), (2, '10'), (2, '010')]

If the second element of each tuple is the string representation of an int in binary, then use int(x, 2) instead of float(x) in the sort key. If they are intended to be the decimal representation of an integer, then use int(x).

https://en.xdnf.cn/q/72958.html

Related Q&A

Tensorboard error: Tensor object has no attribute value

My goal: Add arbitrary text to tensorboard.My code:text = "muh teeeext" summary = tf.summary.text("Muh taaaag", tf.convert_to_tensor(text)) writer.add_summary(summary)My error:File …

How to embed Google Speech to Text API in Python program? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

shell script remote execution using python

Is there a way that I can use Python on Windows to execute shell scripts which are located on a remote Unix machine?P.S: Sorry about the late edit. I do know of Paramiko, but I wanted to know if there…

Shutdown for socketserver based Python 3 server hangs

I am working on a "simple" server using a threaded SocketServer in Python 3.I am going through a lot of trouble implementing shutdown for this. The code below I found on the internet and shut…

How do I url encode in Python?

I tried this: but it doesnt work.print urllib.urlencode("http://"+SITE_DOMAIN+"/go/")I want to turn it into a string with url encodings

resampling pandas series with numeric index

suppose I have a pandas.Series with index with numeric value type e.g. pd.Series( [10,20], [1.1, 2.3] )How do we resample above series with 0.1 interval? look like the .resample func only work on date…

Python3 Tkinter popup menu not closing automatically when clicking elsewhere

Im running Python 3.3.3 (and right now Im on Ubuntu but I also develop on Mac and Windows, which I havent yet tested). I have a Treeview object that responds to right click on items and shows a context…

How does python process a signal?

What is the workflow of processing a signal in python ? I set a signal handler, when the signal occur ,how does python invoke my function? Does the OS invoke it just like C program? If I am in a C e…

Pandas Dataframe to dict grouping by column

I have a dataframe like this:Subject_id Subject Score Subject_1 Math 5 Subject_1 Language 4 Subject_1 Music 8 Subject_2 …

How can I use a Perl module from Python?

There exists a Perl module that provides the perfect functionality for my Python app. Is there any way for me to utilize it? (it is complicated, it would take me a month to port it)I dont want to hav…