首页 > 解决方案 > 打印具有偶数索引号的所有列表元素,错误语句

问题描述

对于我的任务,我认为我已经做对了,但是在 Snakify 上,它向我显示了这个错误语句: Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '1 2 3 4 5' On google colab 这个错误没有出现,在 snakify 上它确实出现了,但是我需要这个错误才能去检查我的解决方案。有什么建议么?

任务是:一个数字列表,查找并打印所有索引号为偶数的列表元素。

a = []
b = []

numbers = input()
for n in numbers.split():
    a.append(int(n))

    if int(n) % 2 == 0:
      b.append(a[int(n)])

print(b)

标签: pythonlistif-statement

解决方案


int()如果参数包含非数字字符,例如空格“”,则只能转换数字并引发错误。您可以使用:

nums = input().split()  # split() method splited string by spaces
a = []
for i in range(len(nums)):  # len() function return count of list elements
    if (i % 2) == 0:
        a.append(nums[i])

print(a)

你也可以得到 IndexError: list index out of range 如果有趣的原因请评论


推荐阅读