Example of how to sort tuples and lists by conditions in Python. Example of python

Source: Internet
Author: User

Example of how to sort tuples and lists by conditions in Python. Example of python

Sort a single tuple in python

My colleague Axel Hecht showed me something I don't know about python sorting. In python, you can sort a single tuple. The example is the best description:

>>> items = [(1, 'B'), (1, 'A'), (2, 'A'), (0, 'B'), (0, 'a')]>>> sorted(items)[(0, 'B'), (0, 'a'), (1, 'A'), (1, 'B'), (2, 'A')]

By default, when the built-in sort and sorted functions receive tuples, they sort the first element of the tuples and then the second element. However, note that (0, 'B') in the result is prior to (0, 'A. This is because uppercase letters B are less ASCII than. However, assume that you want to sort data in a more humane manner and do not focus on Case sensitivity. You may do this:

>>> sorted(items, key=str.lower)Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: descriptor 'lower' requires a 'str' object but received a 'tuple'

We will get an error because it cannot process the first part of the tuples correctly. (Note: the author of the original article estimates that the first item in the tuples is a number and the lower method cannot be used. The correct cause is obvious because you are passing a tuple, the tuples do not use the lower method)

We can try to write a lambda function (eg. sorted (items, key = lambda x: x. lower () if isinstance (x, str) else x), it will not work because you only process one element of the tuples. (Note: As shown above, the author must be wrong when doing so. Think about how to send a tuple to lambda and what is returned ?)

Let's get down to the truth. Here's how you do it. A lambda statement returns a tuples:

>>> sorted(items, key=lambda x: (x[0], x[1].lower()))[(0, 'a'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A')]

Now you have finished it! Thank you for sharing Axel!

I'm sure you know you can sort in reverse order, just use sorted (items, reverse = True ,...), But how do you sort by keywords?

Tips for using lambda functions to return tuples: Below is a slightly advanced data structure for sorting:

>>> peeps = [{'name': 'Bill', 'salary': 1000}, {'name': 'Bill', 'salary': 500}, {'name': 'Ted', 'salary': 500}]

Now, use the lambda function to return the features of a tuples for sorting:

>>> sorted(peeps, key=lambda x: (x['name'], x['salary']))[{'salary': 500, 'name': 'Bill'}, {'salary': 1000, 'name': 'Bill'}, {'salary': 500, 'name': 'Ted'}]

Interesting, right? Bill is in front of Ted and 500 is in front of 1000. But how do I sort salary in reverse order under the same name? It is very easy to reverse it:

>>> sorted(peeps, key=lambda x: (x['name'], -x['salary']))[{'salary': 1000, 'name': 'Bill'}, {'salary': 500, 'name': 'Bill'}, {'salary': 500, 'name': 'Ted'}]

Question: sort the list [[1, 2, 3], [4, 5, 6], [7, 8, 9] into [1, 4, 7], [2, 5, 8], [3, 6, 9]
Analysis:

1. The transformation process is as follows:

1 2 3 1 4 7
4 5 6-> 2 5 8
7 8 9 3 6 9

The transformation process can be seen as the original two-dimensional array row to the new array column, that is, the first row of the original array is extracted as the first column ), the second row is used as the second column )... Of course, you can also regard the transformation process as a row that changes the column of the original array to the new array. This implementation method is not considered for the time being.
2. the original practice is to write two for loops. The outer loop iterates the row of the array in sequence, and the column of the inner loop iterates the array in sequence to implement this inversion process, use the first row of the original array as the first column and the second row as the second column. The procedure is as follows:

In [7]: l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]In [8]: len_row = 3In [9]: len_col = 3In [10]: temp = [[],[],[]]In [11]: for row in l:  ....:   for i in range(len_col):  ....:     temp[i].append(row[i])  ....:   print temp  ....:[[1], [2], [3]][[1, 4], [2, 5], [3, 6]][[1, 4, 7], [2, 5, 8], [3, 6, 9]]In [12]:

Of course, you can also use list derivation. The principle is the same as above. The outer iteration row and the inner iteration col generate a new list:

In [100]: lOut[100]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]In [101]: [[row[col] for row in l] for col in range(len(l[0])) ]Out[101]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Finally, you can use zip to achieve the same purpose:

In [104]: lOut[104]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]In [105]: zip(*l)Out[105]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]In [106]: map(list,zip(*l))Out[106]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

* The combination of this symbol and the list indicates decompression, for example, l = [[1, 2, 3], [4, 5, 6], [7, 8, 9], then I understand that * l is changed to three values: [1, 2, 3], [4, 5, 6], [7, 8, 9, so zip (* l) and zip ([1, 2, 3], [4, 5, 6], [7, 8, 9]) the results will be the same, as shown below:

In [17]: l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]In [18]: zip([1, 2, 3], [4, 5, 6], [7, 8, 9])Out[18]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]In [19]: zip(*l)Out[19]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]In [20]:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.