Problem in understanding Python list comprehensions

前端 未结 6 987
情书的邮戳
情书的邮戳 2021-02-03 13:42

What does the last line mean in the following code?

import pickle, urllib                                                                                                 


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-03 14:09

    Maybe best explained with an example:

    print "".join([e[1] * e[0] for e in elt])
    

    is the short form of

    x = []
    for e in elt:
      x.append(e[1] * e[0])
    print "".join(x)
    

    List comprehensions are simply syntactic sugar for for loops, which make an expression out of a sequence of statements.

    elt can be an arbitrary object, since you load it from pickles, and e likewise. The usage suggests that is it a sequence type, but it could just be anything that implements the sequence protocol.

提交回复
热议问题