Sorting A List of Tuples Question - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Sorting A List of Tuples Question (/thread-2627.html) |
Sorting A List of Tuples Question - richardbl27 - Mar-29-2017 Hi... I am relatively new to Python. I am trying to sort a list of tuples - each tuple contains a boolean variable and a string. I'd like to use the list sort() method... I'm a little confused if I need to use a lambda or use key= or maybe even cmd= I'd like to really do a comparison like cmp((is_present, element.text), (is_present, element.text)) or something similar to compare the tuples. I'm just starting out in my journey with Python so any help or advice you can give would be great. RE: Sorting A List of Tuples Question - zivoni - Mar-30-2017 You can use .sort() to sort list of tuples without any parameters. Python sorts list of tuples lexicographically - at first it sorts it by first elements in tuples, then by second elements (if needed) and so onSo your tuples (bool, str) will be sorted by bool first (all tuples starting with False will be before any tuple starting with True) and then by str. If you need different sorting, you can use key parameter with either lambda or with other function (builtin or your own) - sort applies key function on items and sort is done by returned values. Example:
RE: Sorting A List of Tuples Question - richardbl27 - Mar-30-2017 That is great... thanks so much. |