In Python, is there a way to sort a list of lists and tuples, sequentially?

view a

and b

for me as expected, then why c

is it different? Is there a way to make it compatible with a

and b

without converting everything to a list or tuples?

>>> a = [(1, 0), (0, 0)]
>>> a.sort()
>>> print a
[(0, 0), (1, 0)]
>>>
>>> b = [[1], (0)]
>>> b.sort()
>>> print b
[0, [1]]
>>>
>>> c = [[1, 0], (0, 0)]
>>> c.sort()
>>> print c
[[1, 0], (0, 0)]
>>>

      

+3


source to share


2 answers


You can convert them for sorting purposes only:

>>> c = [[1, 0], (0, 0)]
>>> c.sort(key=tuple)
>>> c
[(0, 0), [1, 0]]

      



That being said, a list containing a combination of lists and tuples is a code smell.

+12


source


If you don't know if the outer container is a list, you can also use:

sorted(c, key=tuple)

      



because c.sort () is a list-only function. Just thought I should add this.

0


source







All Articles