繁体   English   中英

相互比较元组列表,然后使用信息创建新列表

[英]compare list of tuples with eachother then use information to create a new list

所以我有一个包含元组的列表,每个元组在它的零索引中都有一个代码,在第一个索引中有一个名称

[('s530', 'smythe'), ('s530', 'smith'), ('d120', 'davies'), ('d120', 'davis')]

基本上我想做的是将列表中的每个元组与嵌套循环进行比较,并确定哪些名称具有相同的代码。 然后用这个信息构造一行output然后存入一个新的列表

因此,例如,从元组的示例列表中,我想创建一个这样的字符串列表

['smythe and smith have the same code','davies and davis have the same code']
a=[('s530', 'smythe'), ('s530', 'smith'), ('d120', 'davies'), ('d120', 'davis')]

def process(n):
    ret = []
    for i in n:
        for j in n:
            if i==j:
                break
            if i[0]==j[0]:
                ret.append(f"{i[1]} has same code as {j[1]}")
    
    return ret


print(process(a))

这是一个简单的方法,它只是使用了两次嵌套循环并忽略了同一件事

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM