I have a list of integers that I’m using as labels on a graph and I need to represent them in scientific notation. Most of the other questions I see pertain to float values, when the number is like 23.16274586938 but my numbers range from 2600000000 to 2900000000 and need to represent them as 2.61e^8 or whatever for the values. I’ve tried using Decimal, {.2E} and neither of them worked for me. The list has about 50k values in it, with about 12 digits per value.
The solutions I’ve found online only work when you have one single value. Not when iterating over a list.
my list looks like
x = [5160000000000,63720000000000,326723000000000,3400000000000,…] for 50k values
"{:.2e}".format(arr_of_frequencies[i])
Using this, where arr_of_frequencies is my list, or some variations of this give me the error
IndexError: cannot fit 'int' into an index-sized integer
Advertisement
Answer
You can use str.format()
to print a number in scientific notation.
Use str.format()
on a number with “”{:e}” as str to format the number in scientific notation.
To only include a certain number of digits after the decimal point, use “{:.Ne}”, where N is the desired number of digits.
You can further read about formatting here.
For instance:
>>> "{:e}".format(1234566723425254342) >>> '1.234567e+18'
>>> "{:.4e}".format(123456672342525434234232) >>> '1.2346e+23'
For a very big list you can try generators to do transformation with lazy evaluation:
>>> data = open("data.txt", 'r').read() >>> def reverse(data): ... for index in range(len(data)): ... yield "{e}".format(data[index]) ... >>> >>> for x in reverse(data): ... print(x) 3.400000e+12 5.160000e+12 6.372000e+13 3.267230e+14 3.400000e+12 5.160000e+12 6.372000e+13 5.160000e+12 6.372000e+13 3.267230e+14 3.400000e+12 5.160000e+12 6.372000e+13 3.267230e+14 3.400000e+12 5.160000e+12 5.160000e+12 6.372000e+13 3.267230e+14 3.400000e+12 5.160000e+12 6.372000e+13 5.160000e+12 6.372000e+13 3.267230e+14 3.400000e+12 5.160000e+12 6.372000e+13 3.267230e+14 3.400000e+12 5.160000e+12 6.372000e+13 .......50000 entries worked