2014-08-31 72 views
0

我有两个字典。一本字典用于员工服务年限。另一本字典用于一年或少于今年的带薪休假日期的手动规则。此外还包含一个变量,其中包含员工的默认支付休假天数。如何根据列表和字典生成字典

列表1(员工服务年限)

[1,2,3,4,5,6,7,8,9,10] 

这意味着员工工作了10年的全面。

词典(职工放假时间带薪规则)

{ 
3: 15, 
6: 21 
} 

这是什么意思字典是对前3年的员工将获得15天。接下来的三年将收到21天。其余的将是等于默认它是一个变量= 30称为defaultPaidTimeOffDays

输出需要:

{ 
1: 15, 
2: 15, 
3: 15, 
4: 21, 
5: 21, 
6: 21, 
7: 30, 
8: 30, 
9: 30, 
10: 30 
} 

目前代码

def generate_time_off_paid_days_list(self, employee_service_years, rules, default): 

    if not rules: 
     dic = {} 
     for y in employee_service_years: 
      dic[y] = default 
    else: 
     dic = {} 
     last_change = min(rules) 
     for y in employee_service_years: 
      if y in rules: 
       last_change = rules[y] 
      dic[y] = last_change 

    return dic 

但我坚持了越来越如果大=默认

+0

为什么员工服务多年的列表?它不应该只是一个整数,即10? – 2014-08-31 00:51:18

+0

@Asad我正在使用一个列表来轻松遍历它,而不使用range() – Othman 2014-08-31 00:52:56

回答

1

以下是一种可以利用bisect模块确定每年使用哪种规则的方法:

import bisect 

rules = { 
3: 15, 
6: 21 
} 

def generate_time_off_paid_days_list(years, rules, default): 
    r_list = rules.keys() 
    r_list.sort() # sorted list of the keys in the rules dict 
    d = {} 
    for y in years: 
     # First, find the index of the year in r_list that's >= to "y" 
     r_index = bisect.bisect_left(r_list, y) 
     if r_index == len(r_list): 
      # If the index we found is beyond the largest index in r_list, 
      # we use the default 
      days_off = default 
     else: 
      # Otherwise, get the year key from r_list, and use that key to 
      # retrieve the correct number of days off from the rules dict 
      year_key = r_list[r_index] 
      days_off = rules[year_key] 
     d[y] = days_off 
    return d 

print generate_time_off_paid_days_list(range(1,11), rules, 30) 

输出:

{1: 15, 2: 15, 3: 15, 4: 21, 5: 21, 6: 21, 7: 30, 8: 30, 9: 30, 10: 30} 

和更紧凑,而且更可读的版本:

from bisect import bisect_left 

def generate_time_off_paid_days_list(years, rules, default): 
    r_list = sorted(rules) 
    d = {y : default if y > r_list[-1] else 
      rules[r_list[bisect_left(r_list, y)]] for y in years} 
    return d