Python ValueError:以10为基数的int()的文本无效:'['
我正在解决一个问题: 假设我给你一个保存在变量中的列表:a=[1,4,9,16,25,36,49,64,81,100]。写一行Python,它接受这个列表a并生成一个新列表,其中只有这个列表的偶数元素 我写的代码是:Python ValueError:以10为基数的int()的文本无效:'[',python,python-3.x,Python,Python 3.x,我正在解决一个问题: 假设我给你一个保存在变量中的列表:a=[1,4,9,16,25,36,49,64,81,100]。写一行Python,它接受这个列表a并生成一个新列表,其中只有这个列表的偶数元素 我写的代码是: listtt=[] listt=input(‘Please type in the list:') for i in range(int(len(listt))): if (int(listt[i])%2)==0: listtt.append(listt
listtt=[]
listt=input(‘Please type in the list:')
for i in range(int(len(listt))):
if (int(listt[i])%2)==0:
listtt.append(listt[i]) # This will add the number in the given list to the empty list ‘listtt'
else:
pass
print(listtt)
Python显示一个错误:
ValueError:基数为10的int的文本无效:'['
我在StackOverflow的某个地方读到,这意味着Python认为我正在尝试将“[”转换为整数
如何将其覆盖为整数?如何消除此错误?若要过滤偶数,请按以下代码尝试[x代表旧\u列表中的x,如果x%2==0]
In [39]: old_list = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [40]: new_list = [x for x in old_list if x%2==0]
In [41]: new_list
Out[41]: [4, 16, 36, 64, 100]
对于您的代码:
listt=input('Please type in the list:')
# input should be separated with comma ',', without '[' and ']'
listt = listt.split(',')
new_list = [int(x) for x in listt if int(x)%2==0]
print(new_list)
如果用户不键入方括号,则更容易解析用户的输入
evens = []
numbers = input('Please type one or more numbers, separated by commas: ')
for number in numbers.split(','):
if int(number) % 2 == 0:
evens.append(int(number))
print(evens)
谢谢你的帮助!你能告诉我我犯了什么错误以及如何纠正它而不是仅仅告诉我如何纠正它吗?input返回字符串,因此listt是一个字符串。看起来你输入了[1,4,9,16…]作为程序的输入,所以在第一次通过循环时,listt[I]将是第一个字符,一个左方括号。@AaryanDewan listt=input的问题“请在列表中键入:”。这不会得到您想要的,它只会给您一个字符串[1,2,3]@JohnGordon,即使我写listt=listinput“请在列表中键入:”@AaryanDewan调用listinput…也不起作用。它只给您键入的输入的单个字符,按列表而不是一个大字符串排列。它们永远不会转换为整数。语法突出显示应该是一个线索…您使用了错误的acce新界