列表理解语法 [英] List Comprehension Syntax

查看:72
本文介绍了列表理解语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人发现列表理解语法笨拙?


我喜欢它,因为它是一个表达式而不是一系列语句,

但是它看起来有点难以维持。


例如你可以这样做:


result = []

列表中的元素:

如果元素[0:4] == ''blah'':

result.append(element.replace(''blah'',''moof''))


或者只是:


result = [element.replace(''blah'',''moof'')列表中的元素如果

元素[0:4] ==''blah'']


在某些情况下,第二种看起来更干净,但它的可维护性较差。它
倾向于促进长线。这一切似乎都在一起运行等等。并且

通常你需要添加另一个条件或修改它,看起来更好

使用第一种方式,即使它有丑陋的额外init(并且会

导致比列表理解更多的分配?因为它不知道

大小的蝙蝠?)


我我赞成像我认为Guido在风格指南中所说的短线。我好像每条线路一样简单到不需要任何思考就读它,

例如


我更喜欢:


x = c(d,e)

y = f(g,h)

z = b(x,y)

w = a(z)


这样的东西:


w = a(b(c(d,e) ),f(g,h)))


它更易于维护,当你需要进行更改时,只需插入一行,

而不是必须解码一个表达式。


沿着同样的路线,分开一些东西似乎更容易维护。


你可以这样做:


result = [

element.replace(''blah'',''moof'')

列表中的元素

如果元素[0:4] =='''blah'']


我猜,但这对我来说似乎很尴尬。看起来太像for循环和

一个if,然后值在顶部,这对我来说很有趣。

(奇怪地把它放在一行上没有看起来很有趣,但它可以读得更少。或许我只需要习惯它。您更喜欢哪个?

评论?


MB

解决方案

> ;>>>> " Moosebumps" == Moosebumps< cr ** @ crap.crap>写道:


Moosebumps>有没有人在这里找到列表理解语法尴尬?


....


Moosebumps>我赞成像我想的那样短线Guido说

Moosebumps>在风格指南中。我喜欢每一行都这么简单

Moosebumps>至于不需要任何思考阅读它,


您需要考虑拥有几条

行所涉及的总复杂程度。当您看到列表理解时,您知道会发生什么 -

转换和/或应用于列表的过滤。因此,你可以轻松读取和写出野兽。


LC'也鼓励列表转换/过滤方法

问题,我发现这绝对是出色的。手动将元素附加到

列表是单调乏味的,特别是如果问题确实是由LC解决的b / b
定型问题(有趣的是,大多数问题

是;-)。


Moosebumps>你可以这样做:


Moosebumps>结果= [

Moosebumps> element.replace(''blah'',''moof'')

Moosebumps>列表中的元素

Moosebumps> if element [0:4] ==''blah'']


Moosebumps>我想,但这对我来说似乎很尴尬。看起来太多

Moosebumps>像for循环和if,然后值是

Moosebumps>顶部,这对我来说很有趣。 (奇怪地把

Moosebumps>它在一行上看起来并不好笑,但它更少

Moosebumps>可读。)也许我只是习惯了它。

Moosebumps>您更喜欢哪一种?


这只是习惯它的问题。不可否认的是,LC'有时会让新手感到困惑,但他们就是这样一个例子,即新手与非新手友好之间的权衡

已经真正得到了回报。


既然genexps即将到来,你将面临更大的回报
。所以只要继续使用它们,即使它们现在可能感觉不到它们是可维持的。 LC'(和甚至更大程度上的genexps)

几乎是定义pythonic的原因。为我做事的方式

这几天。


-

Ville Vainio http://tinyurl.com/2prnb


Ville Vainio写道:< br>

>>"< Moosebumps" == Moosebumps< cr ** @ crap.crap>写道:



Moosebumps>有没有人在这里找到列表理解语法尴尬?

...

Moosebumps>我赞成像我想的那样短线Guido说
Moosebumps>在风格指南中。我喜欢每一行都这么简单。
Moosebumps>至于不需要任何思考阅读它,

你需要考虑有几个
行所涉及的总复杂性。当您看到列表理解时,您知道会发生什么 -
应用于列表的转换和/或过滤。因此,你可以轻松地阅读和写出野兽。

LC'也鼓励列表转换/过滤方法来解决问题,我觉得这绝对是出色的。手动将元素附加到
列表是很乏味的,特别是如果问题确实是由LC解决的陈规定型问题(有趣的是,大多数问题都是;-)。

Moosebumps>你可以这样做:

Moosebumps>结果= [
Moosebumps> element.replace(''blah'',''moof'')
Moosebumps>列表中的元素
Moosebumps>如果元素[0:4] =='''blah'']

Moosebumps>我想,但这对我来说似乎很尴尬。看起来太多
Moosebumps>像for循环和if,然后值是在Moosebumps>顶部,这对我来说很有趣。 (奇怪地把Moosebumps>它放在一行上看起来并不好笑,但它更少
Moosebumps>可读。)也许我只需要习惯它。
Moosebumps>您更喜欢哪一种?

这只是习惯它的问题。不可否认,LC'有时会让新手感到困惑,但他们就是这种功能的一个例子,新手和非新手友好之间的权衡确实得到了回报。




有人接近25年的编程语言经验

及其含义,我觉得列表理解是不可理解的。

就我个人而言,我认为我的学习受到文件的抑制,这些文件似乎是由列表推理的语法驱动而不是

执行模型以及如何识别它的时间适用于那个

模型。


我发现多条短线实际上更容易理解,因为它将b / b转化为一种常见的心理因素我的模型。当前语法为

那些理解'让我想起了APL,这是一种很棒的语言

如果你想的只是向量。


我会承认这个讨论已经让我试图再次学习列表

comprehensions,因为我正试图解决一个问题,即过滤数据字典的b $ b基于谓词的元素选择

单个元素和/或从上一个谓词列表开始的偏移量的谓词。


顺便说一下,同样受文件限制的是生成器,

迭代器和分析时基。我有很多困难

取出模型抽象,正如我上面所说的那样,了解将

应用于问题空间的位置。
<现在,genexps即将到来,你将面临更大的收益。所以只要继续使用它们,即使它们现在可能感觉不太可能。 LC'(和甚至更大程度上的genexps)
几乎是定义pythonic的原因。为我做事的方式
这些天。




这并不意味着以任何形式或形式挑选你,但我的

经验一直是你发现自己不得不用语言来思考
时,你并没有真正解决正确的问题而且

more可能会使用一系列魔术技巧来混淆和惊讶其他人并且可能确保工作安全。


如果您的模型可以独立于语言实现

并且您可以用问题自然而然的方式表达问题,

您总是可以为跟随您的人提供更好的解决方案

以及机器。


概括,不要pythonize。


--- eric


>>>>> "埃里克" == Eric S Johansson< es*@harvee.org>写道:


Eric>有人接近25年的编程经验

Eric>语言及其含义,我找到列表

Eric>理解是不可理解的。我个人认为我的

Eric>学习受到了抑制。

我发现LC一开始有点奇怪。以前的编程经验

对他们来说可能并不重要,因为他们相当不同。


Eric>似乎由列表语法驱动的文档

Eric>理解而不是执行模型以及如何使用

Eric>认识到何时应用该模型是合适的。


可能。如果文件没有b $ b很好地销售(这是可以解决的,幸运的话),这很容易解雇。我也有点忽略了LC',但是

持续的clpy(由Alex Martelli和其他人)改变了

,对此我很感激和感受荣幸地继续

伪口头传统:-)。


关于列表理解的主要意义是

他们只是提供一种更优雅的方式来做''map''和''过滤''当要应用的

函数不是像str或
$ b $这样的小事b int。 LC的方便性促使人们继续使用地图/过滤器,例如

解决实现新功能的问题(或通过lambda调用

旧的)似乎是不必要的麻烦。


Eric>我发现多条短线实际上更容易理解

Eric>因为它转化为我常见的心理模型。


如果你的心理模型涉及操纵大量的

列表,这会有所帮助。我发现列表操作模型对我很有用,

允许我快速地解决大多数问题(我认为)优雅。我认为这很大程度上取决于你在做什么 - 我的python使用大多是

这些天只是编写脚本(当然不是我控制的原因

;-)。


Eric>我承认这个讨论已经让我试着去试图获得
Eric>再次学习列表理解,因为我正试图解决这个问题。

Eric>过滤数据元素字典的问题

Eric>基于谓词选择单个元素和/或
Eric>从前一个开始的偏移量的谓词

Eric>谓词列表。


对你有好处。使用地图和过滤器(以及使用

闭包的范围内功能)执行此操作,如果感觉更容易,则仅在之后使用LC。我相信

人们对LC的感觉比嵌套示波器更舒服,

因为LC是视觉上的。更多在同一范围内。

"和/或之后的部分现在给出解决方案似乎太神秘了,但似乎除了LC之外你还需要实现一个功能来保持

解决方案的清洁。 />

Eric>顺便说一句,同样受到文件限制的是

Eric>生成器,迭代器和分析时基。我有

Eric>拉出模型抽象有很多困难,而且我需要&b $ Eric $>如上所述,了解在问题中应用它们的位置

Eric>空格。


你觉得这是缺乏的官方文档,还是你尝试过阅读一些Python书籍?我可能已经进入了爱好者的人群,因为他们会阅读那些什么是新的。 docs,PEPs和

这样的?


Eric>经验一直是你发现自己的时候

Eric> 用语言思考,你并没有真正解决问题

Eric>正确的问题,更有可能使用

Eric>神奇的伎俩让别人感到困惑和恐慌

Eric>确保工作安全。


Eric>如果你有可以独立实现的模型

Eric>语言,你可以表达一个问题

Eric>对问题很自然,你总是有一个更好的

Eric>跟随你的人的解决方案以及

Eric>机器。


幸运的是,LC的基础模型非常清楚(map&

过滤器),并且解决了列表处理方式的问题。时间磨练

练习。在让你的朋友惊艳中在前面,LC更多的是看起来像这样优雅和简洁。类型,不是在检查这个

out,所有递归和没有变量,我打赌你甚至不能在

盯着它5分钟后得到它一些学者喜欢的类型。


我想你会发现你不需要牺牲任何旧的模型甚至美学欣赏LC的偏好。


-

Ville Vainio http://tinyurl.com/2prnb


Does anyone here find the list comprehension syntax awkward?

I like it because it is an expression rather than a series of statements,
but it is a little harder to maintain it seems.

e.g. you could do:

result = []
for element in list:
if element[0:4] == ''blah'':
result.append( element.replace( ''blah'', ''moof'' ) )

or just:

result = [ element.replace( ''blah'', ''moof'' ) for element in list if
element[0:4] == ''blah'' ]

The second looks cleaner in some cases, but it is less maintainable. It
tends to promote long lines. It all seems to run together and such. And
often you would need to add another condition or modify it, it seems better
to use the first way even though it has the ugly extra init (and which would
cause more allocs than the list comprehension? because it wouldn''t know the
size off the bat?)

I am in favor of short lines like I think Guido said in the style guide. I
like each line to be so simple as to not require any thinking reading it,
e.g.

I prefer:

x = c( d, e )
y = f( g, h )
z = b( x, y )
w = a( z )

to stuff like this:

w = a( b( c( d, e ), f( g, h ) ) )

It is more maintainable, when you need to make a change, just insert a line,
rather than having to decode an expression.

Along the same lines, it seems more maintainable to split things up.

You could do:

result = [
element.replace( ''blah'', ''moof'' )
for element in list
if element[0:4] == ''blah'' ]

I guess, but that seems awkward to me. Looks too much like a for loop and
an if, and then the value is at the top, which reads funny to me.
(Strangely putting it on one line doesn''t read as funny, but it is less
readable.) Maybe I just have to get used to it. Which do you prefer?
Comments?

MB

解决方案

>>>>> "Moosebumps" == Moosebumps <cr**@crap.crap> writes:

Moosebumps> Does anyone here find the list comprehension syntax awkward?

....

Moosebumps> I am in favor of short lines like I think Guido said
Moosebumps> in the style guide. I like each line to be so simple
Moosebumps> as to not require any thinking reading it,

You need to think of the total complexity involved with having several
lines. When you see a list comprehension, you know what to expect -
transformation and/or filtering applied to a list. Therefore, you can
easily read and write out the beast.

LC''s also encourage the list transformation/filtering approach to
problems, which I find absolutely splendid. Appending elements to a
list manually is tedious, especially if the problem really is a
stereotypical problem solved by a LC (and interestingly, most problems
are ;-).

Moosebumps> You could do:

Moosebumps> result = [
Moosebumps> element.replace( ''blah'', ''moof'' )
Moosebumps> for element in list
Moosebumps> if element[0:4] == ''blah'' ]

Moosebumps> I guess, but that seems awkward to me. Looks too much
Moosebumps> like a for loop and an if, and then the value is at
Moosebumps> the top, which reads funny to me. (Strangely putting
Moosebumps> it on one line doesn''t read as funny, but it is less
Moosebumps> readable.) Maybe I just have to get used to it.
Moosebumps> Which do you prefer?

It''s just a matter of getting used to it. Admittedly LC''s are
sometimes confusing for newbies, but they are an example of such a
feature where the tradeoff between newbie and non-newbie friendliness
has really paid off.

Now that genexps are coming around, you''ll be facing even bigger
payoffs. So just keep using them, even if they might not feel as
maintanable at the moment. LC''s (and genexps even to a bigger extent)
are pretty much what defines the "pythonic" way of doing things for me
these days.

--
Ville Vainio http://tinyurl.com/2prnb


Ville Vainio wrote:

>>"Moosebumps" == Moosebumps <cr**@crap.crap> writes:



Moosebumps> Does anyone here find the list comprehension syntax awkward?

...

Moosebumps> I am in favor of short lines like I think Guido said
Moosebumps> in the style guide. I like each line to be so simple
Moosebumps> as to not require any thinking reading it,

You need to think of the total complexity involved with having several
lines. When you see a list comprehension, you know what to expect -
transformation and/or filtering applied to a list. Therefore, you can
easily read and write out the beast.

LC''s also encourage the list transformation/filtering approach to
problems, which I find absolutely splendid. Appending elements to a
list manually is tedious, especially if the problem really is a
stereotypical problem solved by a LC (and interestingly, most problems
are ;-).

Moosebumps> You could do:

Moosebumps> result = [
Moosebumps> element.replace( ''blah'', ''moof'' )
Moosebumps> for element in list
Moosebumps> if element[0:4] == ''blah'' ]

Moosebumps> I guess, but that seems awkward to me. Looks too much
Moosebumps> like a for loop and an if, and then the value is at
Moosebumps> the top, which reads funny to me. (Strangely putting
Moosebumps> it on one line doesn''t read as funny, but it is less
Moosebumps> readable.) Maybe I just have to get used to it.
Moosebumps> Which do you prefer?

It''s just a matter of getting used to it. Admittedly LC''s are
sometimes confusing for newbies, but they are an example of such a
feature where the tradeoff between newbie and non-newbie friendliness
has really paid off.



as someone approaching 25 years experience with programming languages
and their implications, I find list comprehension''s incomprehensible.
Personally I think my learning is inhibited by the documentation which
seems driven by the syntax of list comprehensions rather than the
execution model and how to recognize when it''s appropriate to apply that
model.

I find multiple short lines actually easier to comprehend because it
translates into a common mental model of mine. The current syntax for
those comprehension''s reminds me of APL which was a wonderful language
if you thought in nothing but vectors.

I will admit this discussion has goaded me into trying to learn list
comprehensions again as I am trying to solve a problem which is
filtering a dictionary of data elements based on predicates selecting
individual elements and/or predicates on the offset from the start of
the previous predicate list.

By the way, similarly hampered-by-the-documentation are generators,
iterators, and profiling time bases. I''m having a lot of difficulty
pulling out model abstractions, and as I said above, understanding where
to apply them in problem spaces.

Now that genexps are coming around, you''ll be facing even bigger
payoffs. So just keep using them, even if they might not feel as
maintanable at the moment. LC''s (and genexps even to a bigger extent)
are pretty much what defines the "pythonic" way of doing things for me
these days.



this is not meant to be picking on you in any way shape or form but my
experience has been that any time you find yourself having to "thinking
in the language", you are not really solving the right problem and are
more likely using a collection of magic tricks to confound and amaze
others and possibly insure job security.

if you have models that can be implemented independent of the language
and you can express a problem in terms that are natural to the problem,
you invariably have a better solution for the people following you as
well as the machine.

generalize, don''t pythonize.

---eric


>>>>> "Eric" == Eric S Johansson <es*@harvee.org> writes:

Eric> as someone approaching 25 years experience with programming
Eric> languages and their implications, I find list
Eric> comprehension''s incomprehensible. Personally I think my
Eric> learning is inhibited by the

I found LC''s a bit odd too at first. Previous programming experience
probably doesn''t matter too much with them, because they are quite
different.

Eric> documentation which seems driven by the syntax of list
Eric> comprehensions rather than the execution model and how to
Eric> recognize when it''s appropriate to apply that model.

Probably. It''s all too easy to dismiss if the documentation doesn''t
sell it well (this is fixable, luckily). I kinda ignored LC''s too, but
persistent ramblings on c.l.py (by Alex Martelli and others) changed
that, for which I''m grateful and feel honor-bound to continue the
pseudo-oral tradition :-).

The main thing to realize about list comprehensions is that
they simply provide a more elegant way to do ''map'' and ''filter'' when a
function to be applied is not something trivial like str or
int. Having LC''s handy urges one to go ahead with map/filter like
approaches to problems where implementing new functions (or calling
old ones via lambda) seems like an unnecessary hassle.

Eric> I find multiple short lines actually easier to comprehend
Eric> because it translates into a common mental model of mine.

It helps if your mental model involves manipulating lots of
lists. I''ve found that the list manipulation model works great for me,
allowing me to solve most problems quickly and (I think) elegantly. I
guess it depends a lot on what you are doing - my python use is mostly
just scripting these days (for reasons not in my control, of course
;-).

Eric> I will admit this discussion has goaded me into trying to
Eric> learn list comprehensions again as I am trying to solve a
Eric> problem which is filtering a dictionary of data elements
Eric> based on predicates selecting individual elements and/or
Eric> predicates on the offset from the start of the previous
Eric> predicate list.

Good for you. Do it with map and filter (and in-scope funcs using
closures) and go LC only afterwards if that feels easier. I believe
people still feel more comfortable with LCs than nested scopes,
because the LC is "visually" more in the same scope. The part after
"and/or" seemed too mysterious to give the solution now, but it seems
you''ll need to implement a function in addition to the LC to keep the
solution clean.

Eric> By the way, similarly hampered-by-the-documentation are
Eric> generators, iterators, and profiling time bases. I''m having
Eric> a lot of difficulty pulling out model abstractions, and as I
Eric> said above, understanding where to apply them in problem
Eric> spaces.

Do you feel it''s the offical docs that are lacking, or have you tried
reading some Python books? I''ve probably been in the "enthusiast"
crowd that gets a kick from reading those "what''s new" docs, PEPs and
such?

Eric> experience has been that any time you find yourself having
Eric> to "thinking in the language", you are not really solving
Eric> the right problem and are more likely using a collection of
Eric> magic tricks to confound and amaze others and possibly
Eric> insure job security.

Eric> if you have models that can be implemented independent of
Eric> the language and you can express a problem in terms that are
Eric> natural to the problem, you invariably have a better
Eric> solution for the people following you as well as the
Eric> machine.

Luckily, the underlying model of LCs is very well understood (map &
filter), and solving things the list-processing way is a time-honed
practice. In the "amaze your friends" front, LCs are more in the "look
how elegant and concise this can be" genre, not in the "check this
out, all recursion and no variables, I bet you can''t get it even after
staring it for 5 minutes" genre loved by some academics.

I think you''ll find that you don''t need to sacrifice any of your old
models or even aesthetic preferences to appreciate LCs.

--
Ville Vainio http://tinyurl.com/2prnb


这篇关于列表理解语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆