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))
如果代碼正常工作,則可能是在此處討論。嘗試提交到https://codereview.stackexchange.com/。 – Chris
我把它壓縮到ya的一行:https://i.fluffy.cc/lv6bGSsq8bVkFRzTwd7ZH0bS6KxP7qnH.html(通過https://github.com/csvoss/onelinerizer) –
做什麼@Chris說。乍一看,我看到兩個'condition'類型,'starts_with_ *'和'* _characters'。您可以將這些循環的邏輯提取到分別接受'start_letter'和'name_length'的函數中。 – Carpetfizz