python - 打印具有偶数索引号的所有列表元素,错误语句
问题描述
对于我的任务,我认为我已经做对了,但是在 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)
解决方案
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
如果有趣的原因请评论
推荐阅读
- javascript - 在引用变量中更改时原始数组未更新
- file - 如何使用 IO::Compress::Zip 在 perl 中压缩文件
- javascript - 错误:部署谷歌云功能时找不到模块“firebase/app”
- python - 如何使用python扭曲图像以形成路径?
- string - 我不知道如何检查字符串在 mips 中是否对称
- python - How to fix the xgboost import error in MacOs?
- excel - 减少具有两行的图表标题中的垂直文本行距
- php - SQLSTATE[21000]:基数违规
- c++ - 调用较少约束的功能等效函数
- c - 走最短路径