gpt4 book ai didi

python - 将列表中的 float 替换为 '0'

转载 作者:行者123 更新时间:2023-12-01 02:23:39 24 4
gpt4 key购买 nike

所以我的编程作业希望我获取用户输入的数字、整数和 float 列表,然后按降序对它们进行排序,并将任何 float 替换为“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))。这允许您通过索引访问实际变量,而对于数字中的数字仅获取值。

这是我的解决方案。我尝试添加评论来解释我这样做的原因,但如果您有任何疑问,请发表评论:

# 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])

关于python - 将列表中的 float 替换为 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47666279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com