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

时间:2017-12-06 03:20:44

标签: python python-3.x

所以我的编程任务要求我输入一个用户输入的数字,整数和浮动列表,然后按降序排序并用“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]

2 个答案:

答案 0 :(得分:1)

说明允许您使用例外。以下内容可以帮助您完成大部分工作。

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

答案 1 :(得分:0)

我所做的一项更改是将所有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])