in ruby:
hash = {'a' => {'abs' => 1}, 'b' => {'abs' => 4}, 'abc' => {'abs' => 6}}
DONT_COUNT_KEYS = ['abc']
sum = 0
hash.collect {|key,value| sum += value['abs'] unless DONT_COUNT_KEYS.include?(key)}
=> [1, 5, nil]
irb(main):007:0> sum
=> 5
我想在一行中在python中做同样的事情。我有什么选择?
each
不适用于字典而values()
不适用于lambda
答案 0 :(得分:3)
您可以在sum
中使用生成器表达式来执行此操作
>>> h = {'a': {'abs':1},
'b': {'abs':4},
'c': {'abs':6},
'd': {'abs':7},
'e': {'abs':3}}
>>> DONT_COUNT_KEYS = 'abc'
>>> sum(value['abs'] for key, value in h.items() if key not in DONT_COUNT_KEYS)
10
答案 1 :(得分:0)
for key, value in hash.items():
sm += value['abs'] if key not in DONT_COUNT_KEYS else 0
或列表理解
[sm += value['abs'] for key, value in hash.items() if key not in DONT_COUNT_KEYS]