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

use*_*655 0 python python-3.x

我正在编写一个脚本来将一个数字返回给一定数量的有效数字.我需要将浮动转换为列表,以便我可以轻松更改数字.这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

这会返回错误:

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
Run Code Online (Sandbox Code Playgroud)

这个错误意味着什么,我怎么能阻止它发生?

tyn*_*ynn 7

你可以这样称呼它list([iterable]),因此可选的需要是可迭代的,而float不是.

iterable 可以是序列,支持迭代的容器,也可以是迭代器对象.

直接定义为列表可行:

n = [float(n)]
Run Code Online (Sandbox Code Playgroud)


the*_*ant -1

尝试将其转换为可迭代对象,因为错误提示了这一点。可迭代对象是您可以访问其中第 i 个元素的东西。你不能对 int、float 等执行此操作。Python 有 list 和 str 来执行此操作。

所以将其转换为 list(obj) 和 iter 或 str(obj)