如何使“ValueError”异常替换列表中的项目

我正在尝试编写一段代码,它将遍历一个数字列表(在竖条上分割),如果用户输入非数字,将抛出异常并用0替换所述对象.它旨在显示列表按降序排列(从大到小),中间有垂直条.

这是我目前的代码,但我无法让它工作.

    numbers = input("Please enter several integer numbers separated by 
    vertical bars. ").split('|')
    for item in numbers:
        try:
            numbers = [int(item) for item in numbers]
        except ValueError:
            item = item.replace(item,'0')
    numbers = sorted(numbers, reverse = True)
    print(' | '.join(str(num) for num in numbers))

最佳答案

numbers = input("Please enter several integer numbers separated by vertical bars. ")
numbers = numbers.split('|')
temp = []
for item in numbers:
    try:
        temp.append(int(item))
    except ValueError:
        temp.append(0)
numbers = temp

请注意,我们在迭代时不会更改数字.完成相同任务的另一种方法是

def eval_number(s):
    try:
        return int(s)
    except ValueError:
        return 0

numbers = input("Please enter several integer numbers separated by vertical bars. ")
numbers = numbers.split('|')
numbers = list(map(eval_number, numbers))
点赞