如何使用for循环
在python中创建字典CPO 1
CL 1
SL 1
EL 1
CPO 1
SL 1
CPO 1
因此预期结果应如下所示 { 'CPO':3 'CL':1, 'SL':2 'EL':1}
我试过了:
avail = defaultdict(list)
cpo = cl = sl= el = 0
for i in hr_line_id:
if i.leave_code == 'CPO':
cpo = cpo + i.no_of_days
avail['cpo'].append(cpo)
elif i.leave_code == 'CL':
cl = cl + i.no_of_days
avail['cl'].append(cl)
elif i.leave_code == 'SL':
sl = sl + i.no_of_days
avail['sl'].append(sl)
print avail
答案 0 :(得分:5)
如@JeanFrancoisFabre所述,这是collections.Counter
的完美示例:
from collections import Counter
text = """CPO 1
CL 1
SL 1
EL 1
CPO 1
SL 1
CPO 1"""
count = Counter()
for line in text.split("\n"):
k,v = line.split()
count[k] += int(v)
print(count)
Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})
如果您需要小写密钥,可以使用count[k.lower()] += int(v)
:
Counter({'cpo': 3, 'sl': 2, 'cl': 1, 'el': 1})
如果数量始终为1
,您只需编写一行代码:
Counter(line.split()[0] for line in text.split("\n"))
# Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})
答案 1 :(得分:4)
我在评论中使用collections.Counter
,但要调整当前代码,这样的事情应该有效:
avail = defaultdict(lambda: 0)
for i in hr_line_id:
if i.leave_code == 'CPO':
avail['cpo'] += i.no_of_days
elif i.leave_code == 'CL':
avail['cl'] += i.no_of_days
elif i.leave_code == 'SL':
avail['sl'] += i.no_of_days
print avail
根据评论,这里的if
链增加了很多噪音。假设目标键不是输入的函数(如.lower()
)和/或您只想允许某组键,这样的东西可能是首选:
avail = defaultdict(lambda: 0)
keyMapping = {
'CPO': 'cpo',
'CL' : 'cl',
'SL' : 'sl'
}
for i in hr_line_id:
if i.leave_code in keyMapping:
avail[keyMapping[i.leave_code]] += i.no_of_days
else:
pass # handle unexpected key
print avail
答案 2 :(得分:1)
使用Counter的这个稍短的版本怎么样?
from collections import Counter
counts = Counter((i.leave_code.lower(), i.no_of_days) for i in hr_line_id)
答案 3 :(得分:1)
以下是使用循环执行此操作的另一种方法:
text = """CPO 1
CL 1
SL 1
EL 1
CPO 1
SL 1
CPO 1"""
text_split = text.split() # split the text [CPO, 1, CL, 1 and so on]
dict_k = text_split[0::2] # values at odd index
dict_v = text_split[1::2] # values at even index
dict_t = {}
for k, v in zip(dict_k, dict_v):
dict_t[k] = dict_t.get(k, 0) + int(v)
print(dict_t)
# output:{'SL': 2, 'CPO': 3, 'EL': 1, 'CL': 1}
答案 4 :(得分:0)
除了计数器,你可以简单地循环。
avail = {}
for i in hr_line_id:
if i.leave_code in avail:
avail[i.leave_code] += i.no_of_days
else
avail[i.leave_code] = i.no_of_days