编写此代码的正确方法是什么?

时间:2021-02-21 15:41:19

标签: python for-loop classification

我试图将年龄分为四组,最好的方法是什么?。 对不起,这个愚蠢的问题,我很菜。 这是我目前所拥有的。

ages = df['Age']
age_groups = {'zero_to_twenty' :[],
             'twenty_one_to_fourty': [],
             'fourty_one_to_sixty': [],
             'sixty_one_and_above': []}
for age in ages:
    if age <= 20:
        age.append(age_groups['zero_to_twenty'])
    if age >=21 <= 40:
        age.append(age_groups['twenty_one_to_fourty'])
    if age >=41 <= 60:
        age.append(age_groups['fourty_one_to_sixty'])
    if age >=61:
        age.append(age_groups['sixty_one_and_above'])

1 个答案:

答案 0 :(得分:1)

首先,您应该使用 elif 来避免不必要的比较。

其次,switch 的性能比许多 if else 语句要好。由于 Python 还没有 match statement(这似乎与 switch 等效),您可以执行以下操作:

group = [
    'zero_to_twenty',
    'twenty_one_to_fourty',
    'fourty_one_to_sixty',
    'sixty_one_and_above'
]
for age in ages:
    if age >= 61: 
        age = 61
    age_groups[group[age // 20]].append(age)