2013/9/17 Piergiuliano Bossi <pgbo...@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. Oltre al fatto che mi da un certo fastidio usare una funzione su una lista che sto percorrendo. Ciao. Marco. -- http://beri.it/ - Un blog http://beri.it/i-miei-libri/ - Qualche libro
_______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python