python list sorting method

1, modify the original list, do not build the sort the new list

  Directly call list sort () method to sort

>>> id(a)
2864146375752
>>> a.sort()
>>> a
[5, 10, 20, 30]
>>> id(a)
2864146375752

>>> a.sort(reverse=True)
>>> a
[30, 20, 10, 5]

>>> id(a)
2864146375752

 

# mess up the order

>>> import random
>>> random.shuffle(a)
>>> a
[20, 10, 30, 5]

>>> id(a)
2864146375752

2, create a new list, the original list unchanged

  Using the built-in function sorted () to sort

>>> id(a)
2864146375752

>>> a = sorted(a)
>>> a
[5, 10, 20, 30]
>>> id(a)
2864146621960

 

 

3, reversed () returns an iterator

The reversed built-in function () also supports the reverse order the list, and a list of object methods reverse () is different,

Built-in function reversed () does not make any changes to the original list, but return an iterator object in reverse order, and the iterator object can only be used once.

>>> c = [20,10,40,4]
>>> a = reversed(c)
>>> a
<list_reverseiterator object at 0x0000029ADC715828>
>>> list(a)
[4, 40, 10, 20]
>>> list(a)
[]

 

Guess you like

Origin www.cnblogs.com/gaojr/p/12129674.html
Recommended