我似乎无法弄清楚这段代码。我写了一个程序,但执行时似乎出现值错误。
我的问题是,根据输入的格式,我收到错误
我正在尝试从列表中读取一系列正整数,然后读取一个负整数。
输入时是这样的:
1 2 3 4 5
-6
它向我显示了一个值错误
但是当它像这样一次输入一个时:
1
2
3
4
5
-6
我得到了所需的输出。
这是注释代码:
#Define a function find_nth_from_end, with parameters 'numbers' for positive numbers and 'n' representing the position fromt the end of the list
def find_nth_from_end(numbers,n):
#Check if N is greater than the len of the list 'numbers'
if n > len(numbers):
#Return the negative of N
return -n
else:
#If N is less than or equal to the range of the list, return the Nth number from end
return numbers[-n]
#Store the main program in def main():
def main():
#create an empty list to store positive numbers in 'numbers'
numbers = []
#Use a 'while' loop to receive the positive number inputs until a negative number is input
while True:
num = int(input())
#Use an if statement to break the loop if num < 0
if num < 0:
#convert negative number to positive number to find N
n = -num
break
#Add positive number to list with .append
numbers.append(num)
#Find the Nth number from the end of the list
result = find_nth_from_end(numbers, n)
#Output result
print(result)
#ensure program is run directly
if __name__ == "__main__":
main()
我已经尝试重写代码好几次了,
这是一个例子:
def main():
numbers=[]
while True:
numbers_list=input()
numbers_int_list= [int(num) for num in numbers_list.split()]
numbers.append(numbers_int_list)
neg_num= int(input())
if neg_num<0:
n = -neg_num
break
numbers.append(neg_num)
result = find_nth_from_end(numbers, n)
print(result)
现在如果我输入这样的数据:
1 2 3 4 5
-6
它将输出-6
但是如果我输入新数据
1 5 9 7 5
-3
当我期望得到 9 作为输出时,我得到了 -3 的输出。
对于第一种情况,如果您输入
1 2 3 4 5
作为输入,变量将存储为字符串“1 2 3 4 5”,不能转换为单个 int
,从而引发值错误。
在第二种情况下,通过将字符串 '1 2 3 4 5' 转换为列表,其中每个元素也从字符串转换为 int,你做得稍微好一些,所以现在你有了正确的
[1, 2, 3, 4, 5]
输入。然而,append
并不像您想象的那样工作。它将整个列表作为单个元素附加到数字的末尾,因此数字变成 [[1, 2, 3, 4, 5]]
而不是 [1, 2, 3, 4, 5]
,后者只有一个元素!所以自然地,要求倒数第 6 个得到 -6。您的第二个输入也会发生同样的情况,因为它仍然只是一个包含 1 个(列表)元素的列表。