Da rafael mir seinen Code zum korrigieren angedreht hat, dachte ich mir, dass ich ihn gleich mal hierher poste, damit mehrere davon was haben.
Code: Alles auswählen
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import division
from sys import argv
# <name> <arbitary amont of names> <how many bit long>
formats = (
('Bit', 2**0),
('Nibble', 2**2),
('Byte', 2**3),
('Kibibyte', 'KB', 'KiB', 2**13),
('Mebibyte', 'MiB', 2**23),
('Gibibyte', 'GiB', 2**33),
('Tebibyte', 'TiB', 2**43),
('Pebibyte', 'PiB', 2**53),
('Exbibyte', 'EiB', 2**63),
('Zebibyte', 'ZiB', 2**73),
('Yobibyte', 'YiB', 2**83)
)
def process_formats_for(formats):
"""Generate a nice dict containing the names and bit sizes"""
format_bytes = dict()
for line in formats:
names = line[:-1]
num_bytes = line[-1]
for name in names:
format_bytes[name] = num_bytes
return format_bytes
def process_formats_expression(formats):
"""another, compatible version (taken straight from hell) specially
made for Y0Gi. Thanks to birkenfeld for explaining me the syntax
of a LC which iterates through two values.
explanation: first splitting the format tuple in names and values
then wrapped in a LC which iterates through the names and creates
new tuples which contain only the pair (name, value).
finaly fed that into dict(), to create a dictionary"""
return dict(
(name, single_format[1]) for single_format in
# split the format in name tuple and bit count
((format[:-1], format[-1]) for format in formats)
for name in single_format[0])
# choose format processor
# choices are uninteresting: for or insane: expression
process_formats = process_formats_expression
format_bytes = process_formats(formats)
def format(value, fmt, new_fmt):
old_size, new_size = format_bytes[fmt], format_bytes[new_fmt]
ratio = old_size / new_size
output = value * ratio
return (output, new_fmt, fmt)
def main():
value = float(argv[1])
output, new_fmt, fmt = format(value, *argv[2:4])
print "%g %s are %g %s" % (value, fmt, output, new_fmt)
if __name__ == '__main__':
main()
Edit: Einige von rafaels Anmerkungen übernommen
Edit: BlackJacks %g-Tipp übernommen.
Edit: Generation des Dicts durch LCs erledigt.
Edit: Y0Gis Vorschlag GEs zu verwenden integriert, Formatleser nun konfigurierbar