python - 如何使用 try 块来捕获文件中没有足够的元素
问题描述
我有这个代码:
lis_ = []
with open(_file) as mylines:
# try: this is for making sure that there enough elements in the file
for line in mylines:
for element in line.split():
try:
s_lines = element.split('/')
s_lines = [int(num) for num in s_lines]
lis_.append(s_lines)
except ValueError:
print('Cannot add to the list: %s' %(s_lines))
#except: im not quite sure what type of exception it would under
这从文件中获取值,并且该文件的值必须都是整数,并且格式如下:
'number'-'number' 输出为 [number(int), number]
我的问题是如何确保该文件中的每个元素都是整数,以及如何确保文件中有足够的日期来制作 10 个列表(所以 10 [number,number] 类型的列表)我认为我解决了确保它们都是数字的部分,但我不太确定如何处理数据限制。
编辑:前
文件的内容是:(这些是需要转换为 int 的字符串)
1-2
3-p
5-6
7-8
9-10
这将导致 2 个错误:1 个 ValueError 因为 p 不是数字,另一个错误(这是我努力捕捉的)是文件中没有足够的数据来制作 10 个列表,如下所示:
[1,2][3,4],[5,6],[7,8],[9,10],(如果有足够的数据), [i,i] [i,i] [i, i] [i,i] [i,i] (所以当有足够的数据时,总共有 10 个单独的列表)
解决方案
在这种情况下,您可以像这样使用断言块
lis_ = []
with open('file') as mylines:
try:
assert len(list(mylines))>=10
for line in mylines:
for element in line.split():
try:
s_lines = element.split('-')
s_lines = [int(num) for num in s_lines]
lis_.append(s_lines)
except ValueError:
print('Cannot add to the list: %s' %(s_lines))
except AssertionError:
print('Not enough data')
如果您想了解更多信息,请使用python assert 关键字
推荐阅读
- javascript - 当我尝试更新时,反应状态总是未定义
- docker - 有没有办法用ubuntu在docker的特定位置安装openjdk-8-jdk?
- bash - 如何使用 shell 脚本中的 echo 命令删除在 jenkins 控制台中生成的空行
- javascript - 如何计算购物车中购物车的总价格?
- regex - 如何在赛普拉斯测试中验证结果是否为 GUID 格式?
- ros - 图片未在 rqt 上查看
- r - 使用 R 构建预测模型
- javascript - JavaScript:按值分组的对象数组的总和值
- javascript - 如何在 React 中处理复选框的 onChange?
- html - Vuejs | 创建使用其中一个道具的中间组件并将所有剩余的东西传播到