将列表中的浮点数替换为"0"



因此,我的编程分配要我获取用户输入的数字,int和浮动的列表,然后按降序订购,然后用" 0"替换任何浮动。我已经完成了重新订购的部分,但替换是让我迷路了。

阅读号码编写一个程序,要求用户在同一条线,被垂直条隔开,周围是零或更多的空间(例如," |"或" |"或" |"或" |")。然后该程序将显示输入的降序的数字(从最大到最小)中的数字,全部在同一条线上,被垂直条和空间隔开(" |")。如果命令行上的任何条目都不是整数编号,程序应将其替换为0。仅使用" for"循环或列表综合。使用异常处理。

# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' : 
").split("|")
# replace the floating numbers with "0"
for number in numbers:
    print(type(number))
    if number.isdigit() == False:
        numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]

我做出的一个更改是将所有for number in numbers切换到for i in range(len(numbers))。这使您可以通过索引访问实际变量,而for number in numbers只能获取值。

这是我的解决方案。我试图添加评论以解释我为什么做我的工作,但是如果您有任何疑问,请发表评论:

# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|'n").split(
    "|")
# strip any extra spaces off the numbers
for i in range(len(numbers)):
    numbers[i] = numbers[i].strip(" ")
# replace the floating numbers and strings with "0"
for i in range(len(numbers)):
    try:
        # check if the number is an int and changes it if it is
        numbers[i] = int(numbers[i])
    except:
        # set the item to 0 if it can't be converted to a number
        numbers[i] = 0
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(reverse = True)
# changes the numbers back into strings
numbers = [str(numbers[i]) for i in range(len(numbers))]
# makes sure that there are more than one numbers before trying
# to join the list back together
if len(numbers) > 1:
    print(" | ".join(numbers))
else:
    print(numbers[0])

指令允许您使用异常。以下内容应该使您大部分时间。

>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>>    try:
>>>        x = int(number)
>>>    except:
>>>        x  = 0
>>>    print(x)
1
0
0
2
0

最新更新