I am plotting the digits of pi on a matplotlib graph, however in order to do this I must split the digits into individual integers. I am using math.pi for this, is there any other way I could do it to make it easier?
I think .split() only works on strings however I may be wrong.
You are correct that strings have a .split()
method and doubles do not.
I think you are thinking about the number as a string, though. Numbers don't really have separate digits, except in their textual representation in some base. So, you could convert the number to a string and go from there.
Eg.
text = "%.20f" % math.pi
digits = [int(s) for s in text if s != "."]
print(digits)
Do you want to split each digit into a list? If so, I would convert it to a string (since numbers are treated as the number itself and not digits that make it up) Then remove the decimal point by making a list that excludes decimal points.
import math
listOfDigits = [item for item in str(math.pi) if item != "."]
You can do this with a generator:
def split_number(number):
number_as_string = str(number)
for character in number_as_string:
if not character.isdigit():
continue
yield int(character)
import math
print(list(split_number(math.pi)))
# [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9]
Or if you prefer a one-liner:
list(int(character) for character in str(math.pi) if character.isdigit())
# or
[int(character) for character in str(math.pi) if character.isdigit()]
I believe these answers are preferable because of the use of isdigit
instead of special-casing only the .
character.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.