在Python中迭代2个索引变量

时间:2015-06-17 01:48:02

标签: python

有更好或更清洁的方法来实现以下结果吗?我有4个条件,一半的代码用" while-loop",i + = 1,j + = 1。

i = 0
j = 0
limit1 = 2
limit2 = 4

while (i < limit1 and j < limit2):
    lists.append ('First index: %d, Second index: %d' % (i, j))
    j += 1
    lists.append ('First index: %d, Second index: %d' % (i, j))
    i += 1
    j += 1

for i in lists:
    print (i)

结果:

First index: 0  Second index: 0
First index: 0  Second index: 1
First index: 1  Second index: 2
First index: 1  Second index: 3

2 个答案:

答案 0 :(得分:2)

j计算i非常简单:

for i in xrange(limit1):
    l.append('First index: %d, Second index: %d' % (i, 2*i))
    l.append('First index: %d, Second index: %d' % (i, 2*i+1))

这假定limit2limit1的两倍。如果情况并非如此,您可以添加额外的支票:

for i in xrange(limit1):
    if 2*i >= limit2:
        break
    l.append('First index: %d, Second index: %d' % (i, 2*i))
    l.append('First index: %d, Second index: %d' % (i, 2*i+1))

或计算预先使用的限制:

for i in xrange(min(limit1, (limit2 + 1)//2)):

虽然你可以看到,限制计算可能容易出错。

请注意,如果limit2不是2的倍数,您的代码可能会为j == limit2发出一个条目:

>>> lists = []
>>> i = 0
>>> j = 0
>>> limit1 = 2
>>> limit2 = 3
>>> while (i < limit1 and j < limit2):
...     lists.append ('First index: %d, Second index: %d' % (i, j))
...     j += 1
...     lists.append ('First index: %d, Second index: %d' % (i, j))
...     i += 1
...     j += 1
...
>>> for i in lists:
...     print (i)
...
First index: 0, Second index: 0
First index: 0, Second index: 1
First index: 1, Second index: 2
First index: 1, Second index: 3

如果不需要,我们可以重新安排循环以j代替i

for j in xrange(min(limit2, limit1*2)):
    l.append('First index: %d, Second index: %d' % (j//2, j))

答案 1 :(得分:1)

lists = ['First index: %d, Second index %d' % (j//2, j) for j in range(limit2) if j//2 < limit1]