0

设置字典:

rr = range(1,11)
ft =[('sd:jan:'+ str(x), 'News') for x in rr]    
fd = dict(ft)

 fd
    {'sd:jan:1': 'News',
     'sd:jan:10': 'News',
     'sd:jan:2': 'News',
     'sd:jan:3': 'News',
     'sd:jan:4': 'News',
     'sd:jan:5': 'News',
     'sd:jan:6': 'News',
     'sd:jan:7': 'News',
     'sd:jan:8': 'News',
     'sd:jan:9': 'News'}

fd.keys()

['sd:jan:10',
 'sd:jan:2',
 'sd:jan:3',
 'sd:jan:1',
 'sd:jan:6',
 'sd:jan:7',
 'sd:jan:4',
 'sd:jan:5',
 'sd:jan:8',
 'sd:jan:9']

如何在键中添加“jan”的所有值?

编辑:我为“jan”的部分键添加值(1+2+3+4+5+6+...+10)。

4

4 回答 4

2

如果你可以避免它,你不应该将数字转换为字符串,如果你想稍后将它们作为数字做一些事情。这个怎么样:

rr = range(1,11)
ft =[(('sd','jan',x), 'News') for x in rr]    
fd = dict(ft)

tot = sum(val
   for (key, subkey, val) in fd
   if subkey == 'jan')

>>>tot
55
于 2012-06-04T18:23:24.120 回答
1

如何使用生成器表达式

sum(int(i.split(':')[-1]) for i in fd.keys())

给出:

55

按 拆分每个条目:,获取最后一个字段,转换为 int 并将它们相加。

In case you'd needed to examine the numbers, or wanted them for some reason later you could easily collect them in a list using list comprehension:

[int(i.split(':')[-1]) for i in fd.keys()]
于 2012-06-04T18:28:34.090 回答
0
len([i for i in fd if i[3:6] == 'jan'])

创建列表推导,通过 'jan' 子字符串 ( [3:6]) 对其进行过滤。使用 计算结果列表len

于 2012-06-04T18:22:58.927 回答
0
for key in fd:
if 'jan' in key:
    total=total+int(key.split(':')[-1])
于 2012-06-04T18:24:26.930 回答