简体   繁体   中英

List Enumeration in Python

The snippet below is from a code tracing exercise.

import copy

def ct1(A, B, C, D, E):
    result = [ ]
    # 0 1 2 3 4 5 6 7 8 9
    pairs = [(A,B),(A,C),(A,D),(A,E),(B,C),(B,D),(B,E),(C,D),(C,E),(D,E)]
    for i,pair in enumerate(pairs):
        (L, M) = pair
        if (L is M): result.append(i)
        elif (L == M): result.append(10*i)

    return result
def f(L):
    L[0] += 1
    return L

A = list(range(3))
B = copy.copy(A)
C, D, E = A, B+[ ], f(B)
print(ct1(A, B, C, D, E))

The part I'm confused about is the enumeration used in the for loop. From the documentation for enumerate() it looks like pair should had have values like:

(0, ([0, 1, 2], [1, 1, 2]))
(1, ([0, 1, 2], [0, 1, 2]))
(2, ([0, 1, 2], [0, 1, 2]))
(3, ([0, 1, 2], [1, 1, 2]))
(4, ([1, 1, 2], [0, 1, 2]))
(5, ([1, 1, 2], [0, 1, 2]))
(6, ([1, 1, 2], [1, 1, 2]))
(7, ([0, 1, 2], [0, 1, 2]))

during the iteration, which means 'L' should have values from 0 through 7 and 'M' , the tuples ([0, 1, 2], [1, 1, 2]) through ([0, 1, 2], [0, 1, 2]) . However when I run this code through the debugger, I see both L and M are lists instead. For example, when i = 0, L = [0, 1, 2] and M = [1, 1, 2] and so forth. Can someone please explain what is going on?

With the line for i,pair in enumerate(pairs): , i gets the index values in the list pairs and goes from 0 to 9 while pair gets the values from the list pairs one by one. So for i = 0 , the pair is ([0, 1, 2], [1, 1, 2]) . Then you call (L, M) = pair and this means L get the first list while M gets the second list in the tuple. Hope this helps.

Of course L and M are lists. If you run

pairs = [(A,B),(A,C),(A,D),(A,E),(B,C),(B,D),(B,E),(C,D),(C,E),(D,E)]
for i, pair in enumerate(pairs):
    print(i, pair)

you will get the desired result. So the tuple you are looking for is saved in pairs . With the line

# ...
(L, M) = pair
# ...

you split up the tuple referenced by pair into its elements, which are – in the first iteration – the two lists referenced by A and B .

The above line essentially means

(L, M) = (A, B)

which is equivalent to

L, M = A, B

which in turn means "assign A to L and assign B to M ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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