简体   繁体   English

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

[英]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然后用这个信息构造一行output然后存入一个新的列表

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这是一个简单的方法,它只是使用了两次嵌套循环并忽略了同一件事

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

相关问题 比较两个元组列表以创建一个包含最大值的新元组 - Compare two list of tuples to create a new tuple containing highest values Python:将字符串列表与元组列表进行比较,并根据匹配或不匹配创建新列表 - Python: Compare list of strings to list of tuples, and create a new list based on match or no match 如何使用现有的元组列表创建新的元组列表 - How to create a new list of tuples with existing list of tuples 嵌套循环通过数据帧并将其字符串列值与字符串元组列表进行比较并有条件地创建一个新列? - Nested loop throuh a datafram and compare it's string column values with a list of string tuples and create a new column conditionally? Python:比较列表和元组列表 - Python: Compare a list and list of tuples .split()和.append将.txt文件中的信息作为元组添加到新列表 - .split() and .append information from .txt file as tuples to a new list 我如何通过划分 python 中的元组列表来创建新的整个列表 - how I create a new whole list by dividing a list of tuples in python 将字符串与元组列表中的元组进行比较 - python - compare string against tuples in list of tuples - python 如果元组为Python,则比较列表中的项目 - Compare items in list if tuples Python 比较元组列表中的几个元素 - compare few elements in list of tuples
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM