I wrote this code to filter a list of names based on certain conditions, and wanted to see if I can reduce this further and eliminate redundancy in code.
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))
dict
s and regexes? Look them up \$\endgroup\$ – Tamoghna Chowdhury Nov 28 '16 at 4:19