Given the Ponto
class, the ordenar
function sorts the list elements by following the following criteria: first value in x
, then y
and finally value in z
.
Beauty, the code works. But I would like to understand how this lambda
expression is "executed in practice" (what it does underneath the cloths, let's say). How can something relatively complex be run in a single line of code?
Complete code:
import random
class Ponto():
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return str(self.x) + ' ' + str(self.y) + ' '+str(self.z)
def cria_pontos(quantos=10):
lista = []
for i in range(quantos):
x = random.randint(0, 100)
y = random.randint(0, 100)
z = random.randint(0, 100)
p = Ponto(x=x, y=y, z=z)
lista.append(p)
return lista
def ordernar(lista=None):
lista.sort(key=lambda p: (p.x, p.y, p.z))
def main():
pontos = cria_pontos(quantos=5)
pontos.append(Ponto(x=1,y=2,z=3))
pontos.append(Ponto(x=2,y=3,z=2))
pontos.append(Ponto(x=2,y=2,z=2))
ordernar(lista=pontos)
for p in pontos:
print(p)
if __name__ == '__main__':
main()
I created this class Ponto
to use as an example to make it easier for me to understand my question. Please do not mind the design of it.