到目前为止还没有找到满意的答案,因此将其作为一个新问题发布。
我必须做以下事情:
我有一个参数,例如test_num = 5
。
现在,在for
循环的单次迭代中,我希望迭代器同时向前和向后运行。
所以作为输出,我想要这样的东西:
Forward is 0, backward is 5.
Forward is 1, backward is 4.
Forward is 2, backward is 3.
Forward is 3, backward is 2.
Forward is 4, backward is 1.
我唯一想到的是:
test_num = 5
for j in range(test_num):
for i in range(test_num, 0, -1):
print "Forward is ", i, ", Backward is ", j
但这显然不是正确的做法。使用zip
是唯一的选择吗?因为zip
仅在我使用相同参数或两个参数相等的情况下才起作用。我正在寻找足够灵活的东西。
答案 0 :(得分:1)
看起来你的代码非常好,但你只需要1个迭代器。
for x in range(5):
print(str(x)+'_'+str(5-x))
这会给你一个正确的想法
答案 1 :(得分:0)
如果您真的想使用两个迭代器,请尝试使用zip()
函数:
for i,j in zip(range(5), range(5, 0, -1)):
print "Forward is {0}, backward is {1}".format(i, j)
#Forward is 0, backward is 5.
#Forward is 1, backward is 4.
#Forward is 2, backward is 3.
#Forward is 3, backward is 2.
#Forward is 4, backward is 1.
但是,您的特定用例似乎很容易使用1迭代器:
for i in range(5)
print "Forward is {0}, backward is {1}".format(i, 5-i)
#Forward is 0, backward is 5.
#Forward is 1, backward is 4.
#Forward is 2, backward is 3.
#Forward is 3, backward is 2.
#Forward is 4, backward is 1.
答案 2 :(得分:0)
最快的解决方案:
test_num = 5
for i in range(test_num):
print("Forward is %d, backward is %d."%(i, test_num-i))
另一个快速解决方案(如果你不使用test_num-i
表达式,我的解决方案):
test_num = 5
for i,j in enumerate(range(test_num,0,-1)):
print("Forward is %d, backward is %d."%(i, j))
另一种使用zip的解决方案(如果你想使用zip!但速度很慢):
test_num = 5
for i,j in zip(range(test_num), range(test_num, 0, -1)):
print("Forward is %d, backward is %d."%(i, j))
<强>基准:强>
timeit.timeit('for i in range(5):pass', number=10000) # 0.004307041002903134
timeit.timeit('for i,j in enumerate(range(5,0,-1)): pass', number=10000) # 0.007563826999103185
timeit.timeit('for i,j in zip(range(5), range(5, 0, -1)): pass', number=10000) # 0.010275325999828056