2013/9/17 Marco Beri <marcob...@gmail.com> > >>> a = [2, -4, 27, 44, 13, 0] >> >>> len(x for x in a if x > 5) >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> TypeError: object of type 'generator' has no len() >> >>> len([x for x in a if x > 5]) >> 3 >> >>> list_max = max(a) >> >>> len([x for x in a if x == list_max]) >> 1 >> >>> len([x for x in a if x == max(a)]) # anche cosi' insomma >> 1 >> > > Per quel che vale, come performance molto, molto meglio la prima versione: > > >>> import timeit > >>> timeit.timeit("len([1 for x in a if x == max(a)])", "a = [2, -4, 27, > 44, 13, 0]") > 5.89989202538311 > >>> timeit.timeit("len([1 for x in a if x == max_a])", "a = [2, -4, 27, > 44, 13, 0];max_a=max(a)") > 1.4572058739309028 > > Circa 4 volte più veloce, come è ovvio visto che fa una volta sola max > invece che 5. >
Si', non ci piove, l'ho solo riportata per completezza, ma non scrivere mai codice cosi'. > > Oltre al fatto che mi da un certo fastidio usare una funzione su una lista > che sto percorrendo. > > Concordo. Ciao, Giuliano -- Piergiuliano Bossi Blog: http://thinkingbox.wordpress.com/ Twitter: http://twitter.com/thinkingbox (English) Twitter: http://twitter.com/scatolapensante (Italiano) Google+: https://plus.google.com/u/0/108187981162465525118
_______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python