PYTHON:从字符串更改列表项

2024-05-29 02:47:13 发布

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

我正在创建一个列表,在其中获取值并将它们转换为浮点值。但是,如果用户输入字符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)来获取要更改为浮点的值?在我的身体里,我也需要一个变量吗?如何在列表中查找字母字符以进行更改?你知道吗

先谢谢你。你知道吗


Tags: ortonumber列表inputmainval字符
2条回答

不能使用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]


一行(不带try/except):
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)]

(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)

谢谢你,埃克洛!你知道吗

相关问题 更多 >

    热门问题