如何使用字典理解来重新编写代码的最后三行?
split2列表的列名称如下。
'年,月,月日,星期几,出生'
split2 = [['1994', '1', '2', '7', '7772'],
['1994', '1', '3', '1', '10142'],
['1994', '1', '4', '2', '11248'],
['1994', '1', '5', '3', '11053'],
['1994', '1', '6', '4', '11406'],
['1994', '1', '7', '5', '11251'],
['1994', '1', '8', '6', '8653'],
['1994', '1', '9', '7', '7910'],
['1994', '1', '10', '1', '10498'],
['1994', '1', '11', '2', '11706'],
['1994', '1', '12', '3', '11567'],
['1994', '1', '13', '4', '11212'],
['1994', '1', '14', '5', '11570'],
['1994', '1', '15', '6', '8660'],
['1994', '1', '16', '7', '8123']]
dayofweek = [int(i[3]) for i in split2]
births = [int(i[-1]) for i in split2]
combine = list(zip(dayofweek, births))
edict = {}
for i in combine:
if i[0] in edict.keys():
edict[i[0]] += i[-1]
else:
edict[i[0]] = i[-1]
print(edict)
output:
{1: 20640, 2: 22954, 3: 22620, 4: 22618, 5: 22821, 6: 17313, 7: 23805}
答案 0 :(得分:2)
这可以做到:
edict = {d: sum(b for w, b in combine if w == d) for d in set(dayofweek)}
由于您希望根据split2
中出现的一周中的每一天(或一组独特的时间)来做出决定,因此您可以遍历set(dayofweek)
,然后在一周的给定日期进行迭代,通过在combine
上进行迭代并匹配日期,并使用生成器将日期的出生日期输出到sum
,来生成当天的dict键,并将其值作为当天的出生日期之和。>
答案 1 :(得分:0)
for i in combine:
edict[i[0]] = edict.get(i[0], 0) + i[1]
但要获得更优雅的解决方案,我会做
for i, v in combine:
edict[i] = edict.get(i, 0) + v
之所以可以这样做,是因为Combine的元素类型为tuple
,并且通过说“ i, v
”可以自动将其拆包
等于说
for i in combine:
i, v = i