我正在解决一个问题:
假设我给你一个保存在变量中的列表: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[i]) # This will add the number in the given list to the empty list ‘listtt'
else:
pass
print(listtt)
Python显示错误:
ValueError: invalid literal for int() with base 10: ‘[‘
我在StackOverflow上的某处读到,这意味着Python认为我正在尝试将’[‘
转换为整数。
我如何尝试将其覆盖为整数?我该如何摆脱这个错误?
答案 0 :(得分:1)
要过滤偶数,请尝试使用以下代码[x for x in old_list if 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)
答案 1 :(得分:1)
如果用户不输入方括号,则可以更轻松地解析用户的输入。
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)