如何组合 range() 函数 [英] How can I combine range() functions

查看:31
本文介绍了如何组合 range() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在编写的某些代码,我需要从 1-30 迭代跳过 6.我天真地尝试的是

For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is

a = range(1,6)
b = range(7,31)

for i in a+b:
    print i

有没有更有效的方法?

推荐答案

在 python 2 中你没有组合范围函数";这些只是列表.你的例子工作得很好.但是 range 总是在内存中创建一个完整的列表,所以如果只在 for 循环中需要,更好的方法可能是使用生成器表达式和 xrange:

In python 2 you are not combining "range functions"; these are just lists. Your example works just well. But range always creates a full list in memory, so a better way if only needed in for loop could be to to use a generator expression and xrange:

range_with_holes = (j for j in xrange(1, 31) if j != 6)

for i in range_with_holes:
    ....

在生成器表达式中,if 部分可以包含要跳过的复杂逻辑.

In generator expression the if part can contain a complex logic on which numbers to skip.

另一种组合迭代的方法是使用itertools.chain:

Another way to combine iterables is to use the itertools.chain:

range_with_holes = itertools.chain(xrange(1, 6), xrange(7, 31))

或者只是跳过不需要的索引

Or just skip the unwanted index

for i in range(1, 31):
    if i == 6:
        continue

    ...

这篇关于如何组合 range() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆