Skip to main content
 首页 » 编程设计

python之查找具有共同元素的元组

2025年05月04日17JustinYoung

假设我有一组包含人名的元组。我想找到所有姓氏相同的人,排除不与其他人分享姓氏的人:

# 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())) 

这看起来丑陋且效率低下。有没有更好的办法?

请您参考如下方法:

defaultdict可用于简化代码:

from collections import defaultdict 
 
def find_family(names): 
    d = defaultdict(list) 
    for fn, ln in names: 
        d[ln].append(fn) 
    return dict((k,v) for (k,v) in d.items() if len(v)>1) 
 
names = set([('John', 'Lee'), ('Mary', 'Miller'), ('Paul', 'Ryan'),  
             ('Bob', 'Ryan'), ('Tina', 'Lee'), ('Bob', 'Smith')]) 
print find_family(names) 

这打印:

{'Lee': ['Tina', 'John'], 'Ryan': ['Bob', 'Paul']}