2016-11-28 122 views
0

我做了一個代碼,根據特定的條件篩選名稱列表..並希望看看我是否可以進一步減少此代碼並消除冗餘。這裏是我的代碼:有沒有辦法減少這段代碼中的行數?

names1 = ["Jane", "Jake", "Bradley", "Bill", "Betty", "Kara", "Kris", "Jil"] 
names2 = ["George", "Kate", "Karen", "Kurt", "Greg", "Gary"] 
selection_criteria = ["full_list", "four_characters", "three_characters", "start_with_k", "start_with_z"] 

def sublist (name_list, condition): 
    return_list = [] 
    if condition == "full_list": 
     return name_list 
    if condition == "four_characters": 
     for name in name_list: 
      if len(name) == 4: 
       return_list.append(name) 
    if condition == "three_characters": 
     for name in name_list: 
      if len(name) == 3: 
       return_list.append(name) 
    if condition == "start_with_k": 
     for name in name_list: 
      if name[0] == 'K': 
       return_list.append(name) 
    if condition == "start_with_z": 
     for name in name_list: 
      if name[0] == 'Z': 
       return_list.append(name) 
    return return_list 

for criteria in selection_criteria: 
    print(sublist(names1, criteria)) 

for criteria in selection_criteria: 
    print(sublist(names2, criteria)) 
+4

如果代碼正常工作,則可能是在此處討論。嘗試提交到https://codereview.stackexchange.com/。 – Chris

+1

我把它壓縮到ya的一行:https://i.fluffy.cc/lv6bGSsq8bVkFRzTwd7ZH0bS6KxP7qnH.html(通過https://github.com/csvoss/onelinerizer) –

+0

做什麼@Chris說。乍一看,我看到兩個'condition'類型,'starts_with_ *'和'* _characters'。您可以將這些循環的邏輯提取到分別接受'start_letter'和'name_length'的函數中。 – Carpetfizz

回答

0

在Python中,如果你發現自己解釋字符串作爲執行函數的名字,你可能會更好剛纔路過的功能本身。您的sublist()函數可以簡單地由內置的filter()函數替代(或者,在Python 3上,也許list(filter(...))可以獲取列表而不是生成器)。您可能的條件列表將變爲:

selection_criteria = [ 
    lambda n: True, # or simply None instead of a lambda 
    lambda n: len(n) == 4, 
    lambda n: len(n) == 3, 
    lambda n: n.startswith("K"), 
    lambda n: n.startswith("Z") 
] 
相關問題