理解 Python 列表推导式的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/501308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:15:07  来源:igfitidea点击:

Problem in understanding Python list comprehensions

pythonlist-comprehension

提问by Léo Léopold Hertz ??

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])

My attempt to the problem:

我对这个问题的尝试:

  • "".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
  • "".join... 使用 join -method 清空文本
  • e[1] * e[0] 将序列中的两个后续值相乘,e
  • 我不确定什么是 e
  • 我不确定这意味着什么,当你在 for 循环之前有一些东西时,比如: e[1] * e[0] for e in elt

回答by Torsten Marek

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 forloops, which make an expression out of a sequence of statements.

列表推导式只是for循环的语法糖,它由一系列语句组成一个表达式。

eltcan be an arbitrary object, since you load it from pickles, and elikewise. The usage suggests that is it a sequencetype, but it could just be anything that implements the sequence protocol.

elt可以是任意对象,因为您从泡菜中加载它,e同样。用法表明它是一种序列类型,但它可以是任何实现序列协议的东西。

回答by Andy Dent

Firstly, you need to put http:// in front of the URL, ie:

首先,您需要将 http:// 放在 URL 前面,即:

handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")

An expression [e for e in a_list]is a list comprehensionwhich generates a list of values.

一个表达式[e for e in a_list]是一个列表理解其产生的值的列表。

With Python strings, the *operator is used to repeat a string. Try typing in the commands one by one into an interpreter then look at data:

对于 Python 字符串,*运算符用于重复字符串。尝试将命令一一输入解释器,然后查看数据:

>>> data[0]
[(' ', 95)]

This shows us each line of data is a tuple containing two elements.

这向我们展示了每一行数据都是一个包含两个元素的元组。

Thus the expression e[1] * e[0]is effectively the string in e[0]repeated e[1]times.

因此,表达式e[1] * e[0]实际上是e[0]重复e[1]次数的字符串。

Hence the program draws a banner.

因此程序绘制了一个横幅。

回答by Nikhil Chelliah

[e[1] * e[0] for e in elt]is a list comprehension, which evaluates to a list itself by looping through another list, in this case elt. Each element in the new list is e[1]*e[0], where eis the corresponding element in elt.

[e[1] * e[0] for e in elt]是一个列表推导式,它通过循环遍历另一个列表来计算列表本身,在本例中为elt。新列表中的每个元素都是e[1]*e[0],其中e是 中的对应元素elt

回答by markhellewell

The question itself has already been fully answered but I'd like to add that a list comprehension also supports filtering. Your original line

问题本身已经得到完整回答,但我想补充一点,列表理解也支持过滤。你原来的线路

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

could, as an example, become

例如,可以成为

print "".join([e[1] * e[0] for e in elt if len(e) == 2])

to only operate on items in elt that have two elements.

仅对 elt 中具有两个元素的项目进行操作。

回答by SilentGhost

join() is a string method, that works on a separator in new string

join() 是一个字符串方法,适用于新字符串中的分隔符

>>> ':'.join(['ab', 'cd'])
>>> 'ab:cd'

and list comprehension is not necessary there, generator would suffice

那里不需要列表理解,生成器就足够了

回答by mechanical_meat

Andy's is a great answer!

安迪的回答很好!

If you want to see every step of the loop (with line-breaks) try this out:

如果您想查看循环的每一步(带有换行符),请尝试以下操作:

for elt in data:
    for e in elt:
        print "e[0] == %s, e[1] == %d, which gives us:  '%s'" % (e[0], e[1], ''.join(e[1] * e[0]))