2014-08-30 115 views
1

所以,我列出了花朵的宽度,高度,x坐标和样式类型。名单如下所示:从嵌套列表中提取数据

list_5 = [[ 43, 440, -120, 'type_D'], 
     [150, 380, -270, 'type_A'], 
     [140, 495, -30, 'type_B'], 
     [180, 450, 300, 'type_E'], 
     [40, 890, 660, 'type_A'], 
     [170, 390, 300, 'type_D'], 
     [140, 360, 30, 'type_F'], 
     [160, 280, -160, 'type_C'], 
     [130, 440, -420, 'type_F'], 
     [260, 330, -390, 'type_B'], 
     [170, 130, -270, 'type_E'], 
     [340, 190, -50, 'type_D'], 
     [200, 210, 265, 'type_C'], 
     [900, 320, 440, 'type_F'], 
     [130, 200, -450, 'type_A']] 

我需要帮助从该列表中获取数据,并使用它在一个函数生成不同类型给出的widthheightx坐标(可以是任何东西)。

例如,如果Type_A具有30一个width,的3030heightx坐标,我将需要为风格甲这些生成的(也可以是红色,并且具有一定的花瓣和纹理)。

到目前为止,我已经创造了这个:

def draw_flowers(parameter_list): 
    pass 

draw_flowers(list_5) 

我不知道如何从列表中,以便给某些类型的列表尺寸提取数据。

+0

详细的输入和输出示例可能会有帮助。 – 2014-08-30 12:33:39

+0

它看起来像你不小心删除了大部分问题内容。我已经恢复了它;没有它,答案就没有多大意义。 – DSM 2014-08-30 17:05:43

回答

2

最Python的方式来写一个开关的情况下使用的字典:

def styleA(width, height, x): 
    # do something 

def styleB(width, height, x): 
    # do something 

def styleC(width, height, x): 
    # do something 

flower_function = { 
    'type_A': styleA, 
    'type_B': styleB, 
    'type_C': styleC 
} 

def draw_flowers(parameter_list): 
    for width, height, x, type in parameter_list: 
     flower_function[type](width, height, x) 
+0

究竟是什么这一说法做: 类型,宽度,高度,X在parameter_list: flower_function【类型】(宽度,高度,X) ,因为它给了我这个错误,当我尝试运行一个测试: 我打印了StyleA函数中宽度height和x的值,当它给出时它给了我(490,-470,Style_F)(50,490) ,-470) – user2747367 2014-08-30 14:53:20

+0

是的,对不起,我的错。现在检查。它是列表解包,例如'a,b = [1,2]'与'a = 1'和'b = 2'相同。所以我正在循环播放你的代码并在组件中解压缩它们。然后我使用'type'来索引'flower_function'并获取相应的函数。最后我可以通过该功能的其他参数。 – 2014-08-30 14:55:32

+0

完美:)谢谢你这么多 – user2747367 2014-08-30 15:03:34

0

据我了解,调度不是仅基于type参数。但可能意味着任意复杂的规则:

" Type_A had a width of 30, height of 30 and x coordinate of 30 =>styleA "

也许你需要某种形式的multimethods,但不仅基于类型,但在价值观吗?

更多的基本用法,这可能做的伎俩:

def styleA(width, height, x, type): 
    pass 

def styleA_ExtraSize(width, height, x, type): 
    pass 

def defaultStyle(width, height, x, type): 
    pass 

def dispatch(width, height, x, type): 
    # The dispatcher is the key element. 
    # Taking benefit of python first-class functions, 
    # it will return one function or the other based on your rules 
    # 
    # Rules might be arbitrary complex as in this example: 

    if width == 30 and height == 30 and x == 30 and type == 'type_A': 
     return styleA 
    elif width > 100 and height > 100 and type == 'type_A': 
     return styleA_ExtraSize 
    # elif 
    #  ... 
    # elif 
    #  ... 
    else: 
     return defaultStyle 

def draw_flowers(lst): 
    for item in lst: 
     handler = dispatch(*item) 
     handler(*item) 

draw_flowers(list_5) 

这种方法的主要优点在于它清楚地分开调度(有你的“规则”的知识),从功能上说适用各种风格。这是缓解测试的必要条件。