0

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

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(',')]
4

3 回答 3

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()功能的其他用途。

于 2013-02-10T22:54:49.547 回答
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')

以重用衡量效率。

于 2013-02-10T23:00:18.503 回答
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(',')]
于 2013-02-10T23:01:02.643 回答