简体   繁体   English

Python中[] []的含义是什么? 是pythonic吗?

[英]What is the [][] meaning in Python? is it pythonic?

I'm reading some Python code like this: 我正在阅读一些这样的Python代码:

import glob
from os.path import *
...
files = glob.glob(prefix + '*') # list out pwd according to some @prefix
res = [f + ['', '/'][isdir(f)] for f in files] # append a `/` to fold

But we can do the append more explicitly: 但是我们可以更明确地执行附加操作:

res = [f + '/' for f in files if isdir(f)]

is the second impl more pythonic ? 第二个impl更pythonic吗? or which one is more efficient? 还是哪个效率更高?


Anyway, after asking the question, I know the orginal impl: 无论如何,问了这个问题之后,我知道了原始含义:

for every f in files , if if is a directory, then isdir will return True , and is the index of '/' in the first list, or False and f append nothing, and f will append '/' or '' according the return value of isdir 对于files每个f ,如果if是目录,则isdir将返回True ,并且是第一个列表中'/'的索引,或者Falsef添加任何内容,并且f将根据情况添加'/'或'' isdir返回值

IMHO, I think the original impl makes newbie comfused with the [][] at the first glance. 恕我直言,我认为最初的印象使新手乍一看就与[][]混淆了。

As noted in the comments, the second implementation is not equivalent. 如评论中所述,第二种实现方式并不等效。 The [,if <filter>] syntax of comprehensions filters out the element from being included at all if the predicate is false. [,if <filter>]推导的语法滤除从被包括在所有如果谓词是假的元素。

A more-readable construct might be 更具可读性的结构可能是

[f + '/' if isdir(f) else f for f in files]

Which leverages a conditional expression in lieu of the [a,b][some_boolean] cruft. 它利用条件表达式代替[a,b][some_boolean]

The two pieces of code that you present do not perform the same task. 您提供的两段代码不会执行相同的任务。 The first lists all matching objects, and appends / to those that are directories. 第一个列出所有匹配的对象,并将/附加到目录中。 The second lists all matching objects that are directories, all with / attached. 第二个列出了所有匹配的对象,它们都是目录,都带有/附加。

So this is something of a non-sequitur. 因此,这是不合时宜的。 It makes no sense to ask which is more Pythonic or more efficient when they perform different tasks. 当他们执行不同任务时,问哪个更Pythonic或更有效是没有意义的。

Is

['', '/'][isdir(f)]

Pythonic? Pythonic? I'm not sure. 我不确定。 In some people's eyes it might be. 在某些人看来,可能是。 I personally find it hard to read. 我个人觉得很难阅读。 At this level of detail much comes down to personal choice. 在这种细节层次上,很多事情取决于个人选择。 Some people would write the code like that, others would not. 有些人会这样写代码,其他人则不会。 You should follow your own instincts. 您应该遵循自己的直觉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM