如何使用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发布于 2017-10-20 12:58:04
我会在注释中使用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发布于 2017-10-20 12:58:06
正如@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})发布于 2017-10-20 13:41:14
这个带有计数器的稍微短一些的版本怎么样?
from collections import Counter
counts = Counter((i.leave_code.lower(), i.no_of_days) for i in hr_line_id)https://stackoverflow.com/questions/46849507
复制相似问题