문제

Let's pretend (since it's true) that I have a Python (3) script that needs to iterate over a 2D array (any length, but each element is just an array of 2 ints, as per the list below).

linCirc  = [[1,10],
            [2, 1],
            [0, 2],
            [2, 2],
            [2, 3],
            [2, 4],
            [2, 0],
            [2, 5]]

I want to iterate over this lovely thing recursively so that

for element in linCirc:
    if element[0] == 0:
        # skip element[1] elements

Essentially, all I need to know is the best way to loop over linCirc, and then when certain conditions are met, instead of going from linCirc.index(element) to linCirc.index(element) + 1, I can control the skip, and skip zero or more elements. For instance, instead of going from [0, 2] to [2, 2], I could go from [0, 2] to [2, 4]. Is this the best way to do this? Should a for loop be involved at all?

For the curious: This code is intended to linearize an electric circuit so that any circuit (with limited components; say, just resistors and batteries for now) can be represented by a 2D array (like linCirc). I will post my full code if you want, but I don't want to clog this up with useless code.

도움이 되었습니까?

해결책

index = 0
while index < linCirc.length:
   if linCirc[index][0] == 0:
       index = index + linCirc[index][1]
   else:
       index = index + 1

Hopefully this provides the functionality you're looking for. Obviously you'll have to add some useful code to this - it just runs from start to end of the array. It may also be helpful to add an index check, to make sure it doesn't run out of bounds when it encounters [0, i] less than i elements from the end of the array.

다른 팁

To support an arbitrary iterable (not just sequences such as list) you could use the consume() recipe:

it = iter(linCirc)
for element in it:
    if element[0] == 0:
       # skip element[1] elements
       n = element[1]
       next(islice(it, n, n), None) # see consume() recipe from itertools docs
    print(element)

example

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top