简体   繁体   English

在Python中使用2个索引变量进行迭代

[英]Iterate with 2 Indexes Variable in Python

Is there a better or cleaner way to achieve the results below? 是否有更好或更清洁的方法来实现以下结果? I have 4 conditions and half of the code is filled with "while-loop", i += 1, and j += 1. 我有4个条件,一半代码填充为“ while循环”,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)

Results: 结果:

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

It's quite straightforward to just compute j from i : 仅从i计算j相当简单:

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))

This assumes limit2 is twice limit1 . 这是假设limit2的两倍limit1 If that isn't always the case, you can add an additional check: 如果并非总是如此,则可以添加其他检查:

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))

or compute which limit to use up front: 或计算预先使用的限制:

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

though as you can see, the limit computation may be error-prone. 尽管如您所见,极限计算可能容易出错。

Note that if limit2 isn't a multiple of 2, your code may emit an entry for j == limit2 : 请注意,如果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

If this isn't desired, we can rearrange the loop to go by j instead of i : 如果不希望这样,我们可以将循环重新排列为j而不是i

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM