简体   繁体   中英

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

so I have a list containing tuples, each tuple has a code in the zero index of it and a name in the first index

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

essentially what i'm trying to do is compare each tuple in list with a nested loop and determine which names have the same code. then use this information to construct a line of output and then store it into a new list

so for instance from the example list of tuples i would want to create a list of strings like so

['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))

this is a simple one it simply uses nested loops twice and ignores the same thing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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