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

时间:2015-05-27 15:29:22

标签: 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)

这将返回错误:

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

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

5 个答案:

答案 0 :(得分:7)

您可以将其称为list([iterable]),因此可选项需要是可迭代的,float不是。

  

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

直接定义为列表可行:

n = [float(n)]

答案 1 :(得分:1)

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.")

答案 2 :(得分:0)

尝试将其转换为可迭代,因为错误表明了这一点。可迭代是您可以访问第i个元素的东西。你不能为int,float等做到这一点.Python有list和str。

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

答案 3 :(得分:0)

我做了一个功能

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)

希望这会有所帮助。

答案 4 :(得分:0)

将所有内容投射到列表的功能

我编写了一个函数,该函数将任何东西(至少是我需要的类型)强制转换为列表。 因此,只需将n = list(n)行替换为n=castToList(n)。 我将其用于pandas DataFrame,以确保列仅包含列表。

演示:

In [99]: print( castToList([1,2]))
[1, 2]

In [100]: print( castToList(np.nan))
[nan]

In [101]: print( castToList('test'))
['test']

In [102]: print( castToList([1,2,'test',7.3,np.nan]))
[1, 2, 'test', 7.3, nan]

In [103]: print( castToList(np.array([1,2,3])) )
[1, 2, 3]

In [104]: print( castToList(pd.Series([5,6,99])))
[5, 6, 99]

代码:

def castToList(x): #casts x to a list
    if isinstance(x, list):
        return x
    elif isinstance(x, str):
        return [x]
    try:
        return list(x)
    except TypeError:
        return [x]


import numpy as np
import pandas as pd
print( castToList([1,2]))
print( castToList(np.nan))
print( castToList('test'))
print( castToList([1,2,'test',7.3,np.nan]))
print( castToList(np.array([1,2,3])) )
print( castToList(pd.Series([5,6,99])))
相关问题