我的任务:
Write a short Python function, minmax(data), that takes a sequence of one or more numbers, and returns the smallest and largest numbers, in the form of a tuple of length two. Do not use the built-in functions min or max in implementing your solution.
代码如下:
def minmax():
data = input("Enter a list of any input > ")
max, min = data[0]
for x in data:
if x > max:
max = x
elif x < min:
min = x
print (max, min)
minmax()
这给了我ValueError:没有足够的值来解包(预期为2,得到1)
。
我该如何解决这个问题?
最佳答案
您使用了错误的语法。我相信您要做的是将 min
和 max
初始化为列表的第一个元素。您使用的赋值用于多重赋值 - 左侧有两个变量,右侧必须有两个值。
但是你想让用户输入的内容都可以;只需分割
您选择的分隔符上的输入,然后将其用于分割
。
此外,请记住将值从字符串转换为整数(留给学生练习)。
您给出的错误的重要语法是
min = max = data[0]
现在您可以继续循环。
关于python - 不断收到 ValueError : not enough values to unpack (expected 2, 得到 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596017/