(Python Basic) 更优雅的字典创建方式

数据挖掘 Python
2022-03-01 20:19:49

有没有更优雅的方式来编写这样的代码?

my_dic = {
    'Model':['Apple', 'Banana', 'Pineapple', 'Melon', 'Orange', 'Grape'], 
    'AAA':[
        method1(y, y_Apple), 
        method1(y, y_Banana), 
        method1(y, y_Pineapple), 
        method1(y, y_Melon),
        method1(y, y_Orange),
        method1(y, y_Grape)]
    ,'BBB':[
        method2(y, y_Apple), 
        method2(y, y_Banana), 
        method2(y, y_Pineapple), 
        method2(y, y_Melon),
        method2(y, y_Orange),
        method2(y, y_Grape)]
    ,'CCC':[
        method3(y,y_Apple), 
        method3(y, y_Banana), 
        method3(y, y_Pineapple), 
        method3(y, y_Melon),
        method3(y, y_Orange),
        method3(y, y_Grape)]
    ,'DDD':[
        method4(y, y_Apple), 
        method4(y, y_Banana), 
        method4(y, y_Pineapple), 
        method4(y, y_Melon),
        method4(y, y_Orange),
        method4(y, y_Grape)]
    ,'EEE':[
        method5(y, y_Apple), 
        method5(y, y_Banana), 
        method5(y, y_Pineapple), 
        method5(y, y_Melon),
        method5(y, y_Orange),
        method5(y, y_Grape)]
} 
3个回答

你可以试试:

my_dic = dict()

my_dic['Model'] = ['Apple', 'Banana', 'Pineapple', 'Melon', 'Orange', 'Grape']
y_list = [y_Apple, y_Banana, y_Pineapple, y_Melon, y_Orange, y_Grape]
keys = zip(['AAA', 'BBB', 'CCC', 'DDD', 'EEE'], ['method1', 'method2', 'method3', 'method4', 'method5'])
func  = lambda F, a, b: eval(F)(a,b)

for name, method in keys:
    my_dic[name] = [ func(method, y, y2) for y2 in y_list]

没有比这更优雅的方法了。这是您需要的可读性和代码大小之间的权衡问题。@aminrd 在代码大小方面提供了一个非常有效的实现,但对人类来说可读性较差。

这也不是这个问题的正确论坛。

这就是我要做的:

model = { # use OrderedDict if you're on python 3.6 or older to preserve ordering
    'Apple': y_Apple,
    'Banana': y_Banana,
    'Pineapple': y_Pineapple,
    'Melon': y_Melon,
    'Orange': y_Orange,
    'Grape': y_Grape,
}

methods = {
    'AAA': method1,
    'BBB': method2,
    'CCC': method3, 
    'DDD': method4,
    'EEE': method5,
} 

my_dic = {
    'Model': list(model.keys()),
    **{k: {meth(y, y_Fruit) for y_Fruit in model.values()} for k, meth in methods.items()}
}