如何将浮点对象转换为列表?

2024-06-01 10:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,将一个数字返回到一定数量的有效数字。我需要把一个浮点数变成一个列表,这样我就可以很容易地改变数字。这是我的代码:

def sf(n,x):
    try:
        float(n)
        isnumber = True
    except ValueError:
        isnumber = False
    if isnumber == True:
        n = float(n)
        n = list(n)
        print(n)
    else:
        print("The number you typed isn't a proper number.")
sf(4290,2)

这将返回错误:

Traceback (most recent call last):
File "/Users/jacobgarby/PycharmProjects/untitled/py package/1.py", line 29, in <module>
sf(4290,2)
File "/Users/jacobgarby/PycharmProjects/untitled/py package/1.py", line 25, in sf
n = list(n)
TypeError: 'float' object is not iterable

这个错误是什么意思,我怎样才能阻止它发生呢?


Tags: pytruenumber错误数字sffloatusers
3条回答

我做了一个函数

def f_to_list(f_variable,num_algorism):
    list1 = []
    n = 0
    variable2 = str(f_variable)
    for i in variable2 :
        list1 += i
    if list1[(num_algorism-1)] == '.' :
        print('banana')
        num_algorism +=1
    list1 = list1[0:(num_algorism )]
    print(list1)

希望这有帮助。

def sf(n,x):
    try:
        float(n)
        isnumber = True
    except ValueError:
        isnumber = False
    if isnumber == True:
        n = float(n)
        n = [n]
        print(n)
    else:
        print("The number you typed isn't a proper number.")

您可以像^{}那样调用它,所以可选的需要是iterable,而float不是

iterable may be either a sequence, a container that supports iteration, or an iterator object.

直接定义为list将起作用:

n = [float(n)]

相关问题 更多 >