有没有办法减少此代码中的行数?

时间:2016-11-28 03:21:59

标签: python

我制作了一个代码来根据某些条件过滤名称列表..并希望看看我是否可以进一步减少这种情况并消除代码中的冗余。这是我的代码:

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))

1 个答案:

答案 0 :(得分: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")
]