How come enumerate does not produce a sequence?
----> 1 BytesInt('1B')
12 def BytesInt(s):
13 suffixes = ['B','KB','MB','GB','TB','PB','EB','ZB','YB']
---> 14 for power,suffix in reversed(enumerate(suffixes)):
15 if s.endswith(suffix):
16 return int(s.rstrip(suffix))*1024**power
TypeError: argument to reversed() must be a sequence
enumerate
indeed does not return a sequence, it is a generator. If your input is relatively small you can convert it to a list:
for power, suffix in reversed(list(enumerate(suffixes))):
enumerate()
produces an iterator, not a sequence. A sequence is addressable (can be subscribed with any index), while an iterator is not.
Either don't use enumerate()
, subtract from len(suffixes)
or convert the enumerate()
output to a list.
Subtraction gives you the advantage of avoiding materialising a list:
for index, suffix in enumerate(reversed(suffixes), 1):
power = len(suffixes) - index
Demo:
>>> def BytesInt(s):
... suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
... for index, suffix in enumerate(reversed(suffixes), 1):
... power = len(suffixes) - index
... if s.endswith(suffix):
... return int(s.rstrip(suffix)) * 1024 ** power
...
>>> BytesInt('1B')
1
>>> BytesInt('1KB')
1024
>>> BytesInt('1TB')
1099511627776
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With