2014-08-31 71 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