避免在存储到字典之前重复检查函数输出

问题描述 投票:0回答:1

我有一个重复的代码块,用于迭代输入,检查一些函数以返回列表,如果函数确实返回列表,则检查填充字典,例如

def some_func(i):
    """ This function returns a filled list of a condition is met, otherwise an empty"""
    return ['abc', 'def'] if i % 2 == 0 else []

i_inputs = [4, 2, 3, 6, 3, 8, 2]
y1 = {}
for i in i_inputs:
    _x = some_funcs(i)
    if _x: 
        y1[i] = _x

主要问题是我的代码中有很多

y
i_inputs
,例如

i_inputs = [4, 2, 3, 6, 3, 8, 2]
y1 = {}
for i in i_inputs:
    _x = some_funcs(i)
    if _x: 
        y1[i] = _x


i_inputs2 = [8, 2, 4, 8, 9, 1]
y2 = {}
for i in i_inputs2:
    _x = some_funcs2(i) # Sometimes another function that also returns a list.
    if _x: 
        y2[i] = _x


i_inputs3 = [4, 8, 2, 9, 9, 1, 5]
y3 = {}
for i in i_inputs3:
    _x = some_funcs3(i) # Yet another function that also returns a list.
    if _x: 
        y3[i] = _x

除了以硬编码方式枚举所有

i_input*
y*
之外,还有更好的方法吗?

python dry
1个回答
0
投票

在函数中抽象模式:

def dict_nonempty(func, l):
    d = {}
    for i in l:
        ret = func(i)
        if ret:
            d[i] = ret

    return d

y1 = dict_nonempty(some_funcs, i_inputs)
y2 = dict_nonempty(some_funcs2, i_inputs2)
y3 = dict_nonempty(some_funcs3, i_inputs3)
© www.soinside.com 2019 - 2024. All rights reserved.