我正在处理一个作业问题,该问题采用逗号分隔值的列表,将其转换为列表,然后对所述列表中的最大值和最小值求和。
def max_min_sum():
user_input = input("Please enter a comma seperated list of numbers")
input_as_a_list = user_input.split(",")
input_as_numbers = map(float, input_as_a_list)
print(sum((min(input_as_numbers))+(max(input_as_numbers, default = 0))))
max_min_sum()
现在我收到此错误:
TypeError: 'float' object is not iterable
我也尝试过:
def max_min_sum():
user_input = input("Please enter a comma seperated list of numbers")
input_as_a_list = user_input.split(",")
input_as_numbers = map(float, input_as_a_list)
print((min(input_as_numbers) + max(input_as_numbers, default = 0)))
max_min_sum()
但是现在它只是给我最小值。
答案 0 :(得分:1)
您的代码中至少有2个错误,请参阅以下注释查看此修复程序:
def max_min_sum():
user_input = input("Please enter a comma seperated list of numbers")
input_as_a_list = user_input.split(",")
# map returns a generator, so you need to consume the output first
# Or, you'll endup with max == 0
# Or, better using a list comprehension
# input_as_numbers = [float(elm) for elm in input_as_a_list]
input_as_numbers = list(map(float, input_as_a_list))
# No need to use sum, you're already using + operator
print(min(input_as_numbers)) + max(input_as_numbers, default = 0))
max_min_sum()