我可以数到100,但使用位掩码将每10次重置为0吗?-还是我错了树?
"""
Required output:
1,2,3,4,5,6,7,8,9,0,1,2,3,4,5...etc repeated 10 times.
"""
reset = 10
for x in range(0, 101):
a = (x ^ reset)
b = x & a
print "Value: %s, %s, %s" % (x, a, b)发布于 2014-04-10 15:15:25
使用mod操作符,%
for x in range(1, 101):
a = x // 10
b = x % 10
print "Value: %s, %s, %s" % (x, a, b)发布于 2014-04-10 15:58:18
这是不可能的应用位掩码。下面的代码示例可以很容易地理解这一点,该示例输出数字6、16、...,96的最后四位。您可以看到,每个数字的位模式是不同的,但是对于每个数字来说,x % 10 == 6是不同的。
所以不管怎么说,你都要评估整个数字。
for x in range(0,100):
if x % 10 == 6:
print (bin(x & 0xf))结果:
0b110
0b0
0b1010
0b100
0b1110
0b1000
0b10
0b1100
0b110
0b0发布于 2014-04-10 16:15:27
如果您想要更快的方式,请考虑使用itertools.cycle
这是我的实验。
from itertools import *
def cycle_iter():
for i in islice(cycle(xrange(10)), 0, 101):
yield i
def cycle_mod():
for x in xrange(0, 101):
yield x % 10
def cycle_mask():
for x in xrange(0, 101):
yield x & 7 & 7#<--It does cycle as 012345670123... And last "& 7" means you need at least one or more operator to generate 01234567890123...测试:
>>> %timeit x = list(cycle_iter())
100000 loops, best of 3: 9.07 us per loop
>>> %timeit x = list(cycle_mod())
100000 loops, best of 3: 10.2 us per loop
>>> %timeit x = list(cycle_mask())
100000 loops, best of 3: 10.9 us per loophttps://stackoverflow.com/questions/22992065
复制相似问题