尝试创建用户输入的int列表。Inerpreter返回"ValueError: invalid with for int() with base 10:“
我是python的新手,我在一个叫做“极客的极客”的网站上练习。Here是我正在处理的问题的链接。本练习的目标是打印用户指定大小的子数组中的第一个负整数。当我试图将用户输入附加到列表中时,解释器给我一个值错误。这显然不是一个类型错误,但是我不知道应该给程序提供什么样的输入才会出现这个错误。输入是在geek上的一个文件中,用于geek的服务器,所以我只能测试我所做的输入。
# This file is for a programing practice exercise of geeksforgeerks.org
# The exercise is first negative int in window of size k
# selecting number of test cases
T = int(input())
for t in range(T):
# initializing array
n = int(input())
arr = []
while n > 0:
arr.append(int(input().strip()))
n-=1
k = int(input())
win = 0 # index of first element in widow subarray
# terminate loop when the window can't extend further
while win < len(array) - k -1:
# boolean for no negatives found
noNeg = True
for i in range(win, k):
if arr[i] < 0:
print(arr[i])
noNeg = False
break
elif i == k-1 and noNeg:
# 0 if last sub arr index reached and found no negs
print(0)
win+=1解释器在第11行显示以下错误:
print(int(input().strip()))
ValueError: invalid literal for int() with base 10: '-8 2 3 -6 10'发布于 2019-10-08 03:02:22
输入数据在同一行上包含多个数字。input()返回一整行输入,当您调用int(input().strip())时,您试图将这一整行解析为一个数字。
您需要在空格中将其拆分。因此,您可以使用以下命令来代替while循环:
arr = map(int, input().strip().split())发布于 2019-10-08 03:02:49
看起来你输入了多个整数,int()不知道如何转换它们-它希望字符串中包含一个整数。您将需要拆分字符串,然后转换为:
Ts = [int(word) for word in input().strip().split(" ")]请注意,这将为您提供一个列表,而不是一个整数。
发布于 2019-10-08 04:09:38
您正在向输入提供多个整数,您可以在第11行使用所需的值扩展数组:
arr = []
arr.extend(map(int, input().strip().split()))
# input: -8 2 3 -6 10输出:
[-8, 2, 3, -6, 10]https://stackoverflow.com/questions/58275563
复制相似问题