简体   繁体   中英

Python - Compare items in list of tuples

I have two lists of tuples (item name, version) - one containing all current items, the other containing items to import. If there is a name clash between imported and current items I want to return the newer version. My solution is:

currentItemVersion = [("ItemA", "001"), ("ItemB", "002"), ("Camera", ""), ("SHD_metal", "001"), ("SHD_wood", "002")]
importItemVersion = [("ItemB", "001"), ("Camera", "001"), ("SHD_metal", "002"), ("SHD_wood", "004")]

def updateItems(currentItems, importItems):
    updatedItems = []
    for i, v in currentItemVersion:
        if i in [n[0] for n in importItemVersion]:
            ni, nv = importItemVersion[[n[0] for n in importItemVersion].index(i)]
            nvInt = int(nv) if nv else -1
            vInt = int(v) if v else -1
            if nvInt > vInt:
                updatedItems.append((ni, nv))
            elif nvInt == vInt:
                updatedItems.append((ni, nv))
            else:
                updatedItems.append((i, v))
        else:
            print('item {0} was not imported'.format(i))
            updatedItems.append((i, v))
    return updatedItems

print(updateItems(currentItemVersion, importItemVersion))

I am wondering if there is a nicer solution for this, especially in lines 7 & 8. Can I somehow check

if i in [n[0] for n in list]

and return n[1] in a single operation?

改为使用dict,这样你就不需要找到内环的键冲突,并将复杂度从O(m * n)降低到O(m)。

You can use a dict and update the items one by one, while checking version by the one that is already in the dict if available, for example:

currentItemVersion = [("ItemA", "001"), ("ItemB", "002"), ("Camera", ""), ("SHD_metal", "001"), ("SHD_wood", "002")]
importItemVersion = [("ItemB", "001"), ("Camera", "001"), ("SHD_metal", "002"), ("SHD_wood", "004")]

def updateItems(currentItems, importItems):
    updated = {}
    for item, ver in currentItems + importItems:
        try:
            if int(ver) > int(updated.get(item, 0)):
                updated[item] = ver

        except ValueError:
            updated[item] = ver

    return updated

print updateItems(currentItemVersion, importItemVersion)

Output:

{'ItemB': '002', 'ItemA': '001', 'Camera': '001', 'SHD_wood': '004', 'SHD_metal': '002'}

dict.get(item, 0) returns version if item is a valid key, and 0 if not. You might want to type cast versions to int() before comparing.

Edit:

Added int() type cast + try/except to catch exception when trying to type cast "" to int()

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