Pythonic Style for Multiline List Comprehension [duplicate]

[亡魂溺海] 提交于 2019-12-18 12:49:21

问题


Possible Duplicate:
Line continuation for list comprehensions or generator expressions in python

What is the the most pythonic way to write a long list comprehension? This list comprehension comes out to 145 columns:

memberdef_list = [elem for elem in from_cache(classname, 'memberdefs') if elem.argsstring != '[]' and 'std::string' in null2string(elem.vartype)]

How should it look if I break it into multiple lines? I couldn't find anything about this in the Python style guides.


回答1:


PEP 8 kinda predates list comprehensions. I usually break these up over multiple lines at logical locations:

memberdef_list = [elem for elem in from_cache(classname, 'memberdefs')
                  if elem.argsstring != '[]' and 
                     'std::string' in null2string(elem.vartype)]

Mostly though, I'd forgo the involved test there in the first place:

def stdstring_args(elem):
    if elem.argstring == '[]':
        return False
    return 'std::string' in null2string(elem.vartype)

memberdef_list = [elem for elem in from_cache(classname, 'memberdefs')
                  if stdstring_args(elem)]


来源:https://stackoverflow.com/questions/12372186/pythonic-style-for-multiline-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!