我尝试将此处的名称键值组合为dict值的键,并将源值计为所述父键的键,并将计数值作为其值。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParentViewController {
if let viewControllers = self.navigationController?.viewControllers {
if (viewControllers.count >= 1) {
let previousViewController = viewControllers[viewControllers.count-1] as! NameOfDestinationViewController
// whatever you want to do
previousViewController.callOrModifySomething()
}
}
}
}
如何实现以下输出?
data = [
{'name':'Gill', 'source':'foo'},
{'name':'Gill', 'source':'foo'},
{'name':'Gill', 'source':'foo'},
{'name':'Gill', 'source':'bar'},
{'name':'Gill', 'source':'bar'},
{'name':'Gill', 'source':'bar'},
{'name':'Gill', 'source':'bar'},
{'name':'Gill', 'source':'bar'},
{'name':'Dave', 'source':'foo'},
{'name':'Dave', 'source':'foo'},
{'name':'Dave', 'source':'foo'},
{'name':'Dave', 'source':'foo'},
{'name':'Dave', 'source':'egg'},
{'name':'Dave', 'source':'egg'},
{'name':'Dave', 'source':'egg'},
{'name':'Dave', 'source':'egg'},
{'name':'Dave', 'source':'egg'},
{'name':'Dave', 'source':'egg'},
{'name':'Dave', 'source':'egg'}
]
我认为有可能使用1班轮......
答案 0 :(得分:7)
按名称使用itertools.groupby
组,然后collections.Counter
计算属于每个名称的来源类别:
from collections import Counter
from itertools import groupby
f = lambda x: x['name']
dct = {k: Counter(d['source'] for d in g) for k, g in groupby(data, f)}
print(dct)
# {'Gill': Counter({'bar': 5, 'foo': 3}), 'Dave': Counter({'egg': 7, 'foo': 4})}
答案 1 :(得分:0)
这显然不是一个单行,但简单而且非常直接。适用于任何数量的值。
results = {}
key = 'name'
for line in data:
tracked_key = line[key]
results.setdefault(tracked_key, {})
for k, v in line.iteritems():
if k == key:
continue
results[tracked_key].setdefault(v, 0)
results[tracked_key][v] += 1