Sort, list.sort() : in-place, sort the index

1. Sort the index of list:

  • sorted() will return a new list without changing original list.

  • sorted can sort (sequence (list, tuple, string) or collection (dictionary, set, frozenset) or (set, frozenset) any other iterator that needs to be sorted.)

return the indices of sorted object(list)

myList = [1, 2, 3, 100, 5]    
x = sorted(range(len(myList)),key=myList.__getitem__)
y = sorted(myList)

# x = [0, 1, 2, 4, 3], y = [1, 2, 3, 5, 100], myList = [1, 2, 3, 100, 5]

# sorting range(len(myList)), that is [0, 1, 2, 3, 4]
# using the values myList.__getitem__(0), myList.__getitem__(1) ..., that is 

# range(len(myList))          0   1   2   3   4 
# myList.__getitem__(id)      1   2   3  100  5

range(len(myList))
# output: range(0,5)

sorting range(len(bb)), that is [0, 1, 2], but using the values -bb[0], -bb[1], -bb[2] as the proxy values.

bb = [10, 5, 20]
sorted(range(len(bb)), key=lambda id: -bb[id])
# range(len(bb))   0   1   2    <-- values
# bb[id]           10   5  20
# -bb[id]         -10  -5 -20    <-- proxy values

# output: [2, 0, 1]

# id is the argument of lambda function, which is every element of range(len(bb)), i.e. 0, 1, 2 

##########################
x = lambda a : a + 10
print(x(5))

2. sort the original list, in-place sort

You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it’s less convenient than sorted() - but if you don’t need the original list, it’s slightly more efficient.

>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]

https://docs.python.org/3.3/howto/sorting.html

3. __getitem__

list __getitem__ :

the[]syntax for getting item by key or index is just syntax sugar. When you evaluatea[i]Python callsa.__getitem__(i)

(ortype(a).__getitem__(a, i) Even if the class ofamay not explicitly define this method, it is usually inherited from an ancestor class.
https://stackoverflow.com/questions/43627405/understanding-getitem-method

results matching ""

    No results matching ""