类似字符串处理的DRY版本

时间:2013-02-10 22:52:21

标签: python

执行以下操作的更有效方法是什么:

directors = get_element_or_none(title_node, 'Director')
producers = get_element_or_none(title_node, 'Producer')
writers = get_element_or_none(title_node, 'Writer')

if directors:
    directors = [director.strip() for director in directors.split(',')]
if producers:
    producers = [producer.strip() for producer in producers.split(',')]
if writers:
    writers = [writer.strip() for writer in writers.split(',')]

3 个答案:

答案 0 :(得分:1)

总是生成一个列表(可能是空的):

directors = [director.strip() for director in directors.split(',')] if directors else []
# etc.

或使用map(str.strip, ...)

directors = map(str.strip, directors.split(',')) if directors else []

但在Python 3中需要显式调用list()

directors = list(map(str.strip, directors.split(','))) if directors else []

因为map()会返回迭代器。

或使用帮助函数:

def tolist(commaseparated):
    return [s.strip() for s in commaseparated.split(',')] if commaseparated else []

directors = tolist(directors)
producers = tolist(producers)
writers   = tolist(writers)

或者,使用地图版本:

def tolist(commaseparated):
    return map(str.strip, commaseparated.split(',')) if commaseparated else []

分割和剥离操作可能会与get_element_or_none()调用合并为一个函数,但这取决于您可能使用tolist()功能的其他内容。

答案 1 :(得分:0)

不是很激进但是:

def clean_element(node, tag):
    elements  = get_element_or_none(node, tag)
    if elements:
        elements = [element.strip() for element in elements.split(',')]
    return elements


directors = clean_element(title_node, 'Director')
producers = clean_element(title_node, 'Producer')
writers   = clean_element(title_node, 'Writer')

像两轮车一样激进。

import functools
get_them  = functools.partial(clean_element, title_node)

directors = get_them('Director')
producers = get_them('Producer')
writers   = get_them('Writer')

重用中衡量的效率。

答案 2 :(得分:0)

如果你的意图是干的 - 就像不重复某些事情并引入更多错误机会一样 - 这样的事情怎么样:

cast={}
for title in ('Director','Prodcer','Writer'):
    name=get_element_or_none(title_node, title)
    if name:
        cast [title]=[x.strip() for x in name.split(',')]