2011/1/11 Vittorio Zuccala' <vittorio.zucc...@gmail.com> > Buongiorno a tutti, > vi scrivo su un parere su un algoritmo... > Ho un file con una serie di numeri che in qualche modo recupero. > Questi numeri rappresentano byte, Kb, Mb, Gb, Tb... > Vorrei trasformarli in modo leggibile. > Ad esempio (posso immagazzinarli in un array, dizionario o altro... non > importa): > > 172183142400=>172,1Gb > 250057060352=>250,0Gb > 132450=>132,4Kb > > e così via. > L'operazione è di per sè semplice ma l'ho risolta con una serie di if. > Se maggiore di 1000, dividi per mille, e mettici kb a fianco. > Se maggiore di 1000.000..... > > Secondo voi c'è un modo più elegante o meno "dispendioso"? > Grazie in anticipo... > > Ciao, io propongo questo: import math u='KMGTP' #faccio una lista di numeri fino a 10**15 L=[3.14159 * 10**n for n in range(15)]
for x in L: n=int(math.log10(x)) k=n//3 x1=x/(10**(k*3)) print "%s --> %.1f %s"%(x,x1,u[k]+'B') Che da come output: >>> for x in L: ... n=int(math.log10(x)) ... k=n//3 ... x1=x/(10**(k*3)) ... print "%s --> %.1f %s"%(x,x1,u[k]+'B') ... 3.14159 --> 3.1 KB 31.4159 --> 31.4 KB 314.159 --> 314.2 KB 3141.59 --> 3.1 MB 31415.9 --> 31.4 MB 314159.0 --> 314.2 MB 3141590.0 --> 3.1 GB 31415900.0 --> 31.4 GB 314159000.0 --> 314.2 GB 3141590000.0 --> 3.1 TB 31415900000.0 --> 31.4 TB 314159000000.0 --> 314.2 TB 3.14159e+12 --> 3.1 PB 3.14159e+13 --> 31.4 PB 3.14159e+14 --> 314.2 PB Se vuoi qualcosa di piu' compatto: n=lambda x: int(math.log10(x))//3 T=["%.1f %s"%(x/(10**(n(x)*3)),u[n(x)]+'B') for x in L] e T e' la lista dei risultati: >>> T=["%.1f %s"%(x/(10**(n(x)*3)),u[n(x)]+'B') for x in L] >>> T ['3.1 KB', '31.4 KB', '314.2 KB', '3.1 MB', '31.4 MB', '314.2 MB', '3.1 GB', '31.4 GB', '314.2 GB', '3.1 TB', '31.4 TB', '314.2 TB', '3.1 PB', '31.4 PB', '314.2 PB'] Ciao Stefano > _______________________________________________ > Python mailing list > Python@lists.python.it > http://lists.python.it/mailman/listinfo/python > >
_______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python