python: using list slice as target of a for loop

后端 未结 3 1580
孤城傲影
孤城傲影 2020-12-11 03:27

I found this code snippet to be very interesting.

a = [0, 1, 2, 3]

for a[-1] in a:
    print(a)

Output is as follows:

[0,          


        
3条回答
  •  时光说笑
    2020-12-11 03:52

    What happens is

             0 SETUP_LOOP              24 (to 26)
              2 LOAD_GLOBAL              0 (a)
              4 GET_ITER
        >>    6 FOR_ITER                16 (to 24)
              8 LOAD_GLOBAL              0 (a)     //ARRAY (TOS1)
             10 LOAD_CONST               2 (-1)    //DEST (TOS)
             12 STORE_SUBSCR                       //ARRAY[DEST] = TOS2*
            14 LOAD_GLOBAL              1 (print)
             16 LOAD_GLOBAL              0 (a)
             18 CALL_FUNCTION            1
             20 POP_TOP
             22 JUMP_ABSOLUTE            6
        >>   24 POP_BLOCK
        >>   26 LOAD_CONST               0 (None)
             28 RETURN_VALUE
    

    *So if someone could clarify that TOS2 is actually the 'visited' value of the ARRAY?

提交回复
热议问题