理解Python列表理解的问题 [英] Problem in understanding Python list comprehensions
本文介绍了理解Python列表理解的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码中的最后一行是什么意思?
What does the last line mean in the following code?
import pickle, urllib
handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")
data = pickle.load(handle)
handle.close()
for elt in data:
print "".join([e[1] * e[0] for e in elt])
我对问题的尝试:
- ".join ...使用join方法来清空文本
- e [1] * e [0]将序列中的两个后继值相乘
- 我不确定什么是e
- 我不确定,-loop之前有什么内容,例如:
e[1] * e[0] for e in elt
- "".join... uses join -method to empty text
- e[1] * e[0] multiplies two subsequent values in the sequence, e
- I am not sure what is e
- I am not sure, what it means, when you have something before for -loop, like:
e[1] * e[0] for e in elt
推荐答案
也许最好用一个例子来解释:
Maybe best explained with an example:
print "".join([e[1] * e[0] for e in elt])
是
x = []
for e in elt:
x.append(e[1] * e[0])
print "".join(x)
列表推导只是用于for
循环的语法糖,它从语句序列中生成表达式.
List comprehensions are simply syntactic sugar for for
loops, which make an expression out of a sequence of statements.
elt
可以是任意对象,因为您是从泡菜中加载的,e
也是如此.用法表明它是序列类型,但可以是实现序列协议的任何东西.
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.
这篇关于理解Python列表理解的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文