2014-08-30 142 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) 

這種方法的主要優點在於它清楚地分開調度(有你的「規則」的知識),從功能上說適用各種風格。這是緩解測試的必要條件。