小编jr0*_*r0d的帖子

python任意增加循环内的迭代器

我可能以错误的方式解决这个问题,但我想知道如何在python中处理这个问题.

首先是一些c代码:

int i;

for(i=0;i<100;i++){
  if(i == 50)
    i = i + 10;
  printf("%i\n", i);
}
Run Code Online (Sandbox Code Playgroud)

好的,所以我们永远不会看到50年代......

我的问题是,如何在python中做类似的事情?例如:

for line in cdata.split('\n'):
  if exp.match(line):
    #increment the position of the iterator by 5?
    pass
  print line
Run Code Online (Sandbox Code Playgroud)

由于我在python方面的经验有限,我只有一个解决方案,介绍一个计数器和另一个if语句.在exp.match(line)为真之后,打破循环直到计数器达到5.

必须有一个更好的方法来做到这一点,希望是一个不涉及导入另一个模块的方法.

提前致谢!

python iterator

48
推荐指数
2
解决办法
4万
查看次数

Python异常处理

C有perror和errno,它打印并存储遇到的最后一个错误.这在执行文件io时很方便,因为我不必将fstat()作为fopen()参数失败的每个文件向用户提供调用失败的原因.

我想知道在python中优雅地处理IOError异常时获取errno的正确方法是什么?

In [1]: fp = open("/notthere")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

/home/mugen/ in ()

IOError: [Errno 2] No such file or directory: '/notthere'


In [2]: fp = open("test/testfile")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

/home/mugen/ in ()

IOError: [Errno 13] Permission denied: 'test/testfile'


In [5]: try:
   ...:     fp = open("nothere")
   ...: except IOError:
   ...:     print "This failed for some reason..."
   ...:     
   ...:     
This failed for some reason...

python exception errno ioerror

21
推荐指数
3
解决办法
6万
查看次数

标签 统计

python ×2

errno ×1

exception ×1

ioerror ×1

iterator ×1