简体   繁体   English

其中哪一个更像python?

[英]Which of these is more python-like?

I'm doing some exploring of various languages I hadn't used before, using a simple Perl script as a basis for what I want to accomplish. 我正在探索一些以前从未使用过的语言,使用一个简单的Perl脚本作为我要完成的工作的基础。 I have a couple of versions of something, and I'm curious which is the preferred method when using Python -- or if neither is, what is? 我有一些版本的东西,我很好奇在使用Python时哪种方法是首选方法,或者如果都不是,那是什么?

Version 1: 版本1:

workflowname = []
paramname = []
value = []
for line in lines:
        wfn, pn, v = line.split(",")
        workflowname.append(wfn)
        paramname.append(pn)
        value.append(v)

Version 2: 版本2:

workflowname = []
paramname = []
value = []
i = 0;
for line in lines:
        workflowname.append("")
        paramname.append("")
        value.append("")
        workflowname[i], paramname[i], value[i] = line.split(",")
        i = i + 1

Personally, I prefer the second, but, as I said, I'm curious what someone who really knows Python would prefer. 就个人而言,我更喜欢第二种,但正如我所说,我很好奇真正了解Python的人会喜欢什么。

A Pythonic solution might a bit like @Bogdan's, but using zip and argument unpacking Pythonic解决方案可能有点像@Bogdan,但使用zip和参数解压缩

workflowname, paramname, value = zip(*[line.split(',') for line in lines])

If you're determined to use a for construct, though, the 1st is better. 但是,如果确定要使用for构造,则1st更好。

Of your two attepts the 2nd one doesn't make any sense to me. 在您的两次尝试中,第二次对我没有任何意义。 Maybe in other languages it would. 也许会用其他语言。 So from your two proposed approaces the 1st one is better. 因此,从您提出的两种方法中,第一种更好。

Still I think the pythonic way would be something like Matt Luongo suggested. 我仍然认为,pythonic的方式会像Matt Luongo所建议的那样。

Bogdan's answer is best. 博格丹的答案是最好的。 In general, if you need a loop counter (which you don't in this case), you should use enumerate instead of incrementing a counter: 通常,如果需要循环计数器(在这种情况下不需要),则应使用enumerate而不是增加计数器:

for index, value in enumerate(lines):
    # do something with the value and the index

Version 1 is definitely better than version 2 (why put something in a list if you're just going to replace it?) but depending on what you're planning to do later, neither one may be a good idea. 版本1绝对比版本2更好(如果要替换它,为什么要在列表中放一些东西?),但是取决于您以后打算做什么,这两个都不是个好主意。 Parallel lists are almost never more convenient than lists of objects or tuples, so I'd consider: 并行列表几乎从来没有比对象或元组的列表更方便的,因此我考虑:

# list of (workflow,paramname,value) tuples
items = []
for line in lines:
    items.append( line.split(",") ) 

Or: 要么:

class WorkflowItem(object):
    def __init__(self,workflow,paramname,value):
        self.workflow = workflow
        self.paramname = paramname
        self.value = value

# list of objects
items = []
for line in lines:
    items.append( WorkflowItem(*line.split(",")) ) 

(Also, nitpick: 4-space tabs are preferable to 8-space.) (此外,nitpick:4空格制表符比8空格要好。)

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

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