PYTHON:将列表项从字符串更改为float

时间:2015-11-18 22:24:30

标签: python string list floating-point

我正在创建一个列表,在其中我获取值并将它们转换为浮点数。但是,如果用户输入字符A-Z / a-z,我必须将该值更改为0.0并指定值已更改的位置。这是我遇到麻烦的地方。我不确定如何找到值并将它们更改为0.0,如果它们不是数字的话。到目前为止,这是我的代码:

def main():
    # Creating the list
    num_list = []
    val = input("Enter a number or 0 to stop: ") 

    while val != '0': 
        num_list += [val] 
        val = input("Enter a number or 0 to stop: ") 
    #The list before values are changed to floats    
    print("Before: ", num_list) 

    try: 
        if val.isdigit():
            newnumlist = [] 
            for val in list:
                newnumlist.append(float(val)) 
        print(newnumlist)
    except ValueError: 

main()

在我的try语句之后,我不断收到TypeError。我是否需要使用变量(例如i)来获取要更改为浮点数的值?在我的身体中,我还需要一个变量吗?如何更改列表中的字母字符?

提前谢谢你。

2 个答案:

答案 0 :(得分:2)

(1)改变

for val in list:

for val in num_list:

(2)改变

except ValueError:

except ValueError:
    pass

(或者你想让程序在发生ValueError时做的任何事情)。

这将有效:

try:
    newnumlist = []
    for val in num_list:
        if val.isdigit():
            newnumlist.append(float(val))
        else:
            newnumlist.append('0.0')
    print(newnumlist)
except ValueError:
    pass

但是,我觉得你正试图了解异常,所以试试(双关语):

newnumlist = []
for val in num_list:
    try:
        newnumlist.append(float(val))
    except ValueError:
        newnumlist.append('0.0')

print(newnumlist)

感谢ekhumoro!

答案 1 :(得分:-1)

您无法使用isdigit来测试字符串是否为浮点数。您需要将其设为自己,然后使用此功能映射列表:

def parse(string):
    try:
        return float(string)
    except Exception:
        raise TypeError

old_list = ["3.2","2.1"]
new_list = [parse(i) for i in old_list]

<小时/> 一行(没有尝试/除外):

new_list = list(map(float,old_list))
# or other style
new_list = [float(i) for i in old_list] # certainly faster

它完全相同(肯定更慢):

new_list = []
for i in old_list:
    new_list += [float(i)] # or [parse(i)]