假设我有一组包含人名的元组。我想找到大家谁分享相同的姓氏,排除人谁不向任何人透露自己的姓氏:查找具有公共元素的元组
# input
names = set([('John', 'Lee'), ('Mary', 'Miller'), ('Paul', 'Ryan'),
('Bob', 'Ryan'), ('Tina', 'Lee'), ('Bob', 'Smith')])
# expected output
{'Lee': ['Tina', 'John'], 'Ryan': ['Bob', 'Paul']} # or similar
这是我在用
def find_family(names):
result = {}
try:
while True:
name = names.pop()
if name[1] in result:
result[name[1]].append(name[0])
else:
result[name[1]] = [name[0]]
except KeyError:
pass
return dict(filter(lambda x: len(x[1]) > 1, result.items()))
这看起来丑陋和低效。有没有更好的办法?
(+1)这就是我要做的 – inspectorG4dget 2012-02-02 19:12:08