首页 > 解决方案 > 使用列表列表并进行一些比较 Python

问题描述

我不知道如何比较 2 个不同的列表并写下我需要的内容:我有一个列表。我需要检查 3 件事。首先,如果item[1], item[2]ofeste_mes item在列表中resto并将完整添加itemchanges. 其次,如果item[1], item[2]ofeste_mes item不在 the 中resto,添加到news和 for the item[1], item[2]of resto itemare not este_mes,添加到lost

este_mes = [
    ['1', 'A', 'a', '300'],
    ['1', 'B', 'b', '30'], 
    ['1', 'C', 'c', '100'], 
    ['1', 'D', 'd', '4500']]

resto = [
    ['2', 'A', 'a', '3'],
    ['2', 'B', 'b', '302'], 
    ['2', 'X', 'x', '98'], 
    ['2', 'Z', 'z', '276'], 
    ['3', 'A', 'a', '54'], 
    ['3', 'B', 'b', '65'], 
    ['3', 'F', 'f', '76'], 
    ['3', 'Y', 'y', '99']]

# I need something like this but I don't know how can I do it!

changes = []
news = []
lost = []

for item in este_mes:
    if item[1] and item[2] are in some item of resto:
        changes.append(item_resto)
    if item[1] and item[2] are not in some item of resto:
        news.append(item)
for item in resto:
    if item[1] and item[2] are not in item of este_mes:
        lost.append(item_resto)

答案应该是:

news = [['1', 'C', 'c', '100'],
        ['1', 'D', 'd', '4500']]
lost = [['2', 'X', 'x', '98'],
        ['2', 'Z', 'z', '276'],
        ['3', 'F', 'f', '76'],
        ['3', 'Y', 'y', '99']]
changes = [['2', 'A', 'a', '3'],
           ['2', 'B', 'b', '302'],
           ['3', 'A', 'a', '54'],
           ['3', 'B', 'b', '65']]

这是答案:

este_mes = []
resto = []
changes = []

for item in este_mes:
    for rest in resto:
        if (item[1] == rest[1] and item[2] == rest[2]):
            rest = [rest[0]] + [item[1]] + [item[2]] + ([float(item[3]) - float(rest[3])])
            changes.append(rest)
            resto.remove(rest)

标签: python

解决方案


我已经评论了代码,所以希望你能遵循逻辑。

#initialise our lists
news = []
changes = []
lost = []
#iterate over each list in `este_mes`
for l in este_mes:
    #matches marks whether we have matched in `resto`
    matched = False
    for ll in resto:
        if l[1] == ll[1] and l[2] == ll[2]:
            #we matched, so append list from `resto` to changes
            changes.append(ll)
            matched = True
    #if there were no matches, append the `este_mes` list to `news`
    if not matched:
        news.append(l)

#iterate over lists in `resto` to look for ones to add to `lost`
for l in resto:
    #check to see if there are any matches in `este_mes`
    for ll in este_mes:
         if l[1] == ll[1] and l[2] == ll[2]:
             break
    else:
         #this `else` clause is run if there was no `break` -
         #indicates that no matches were found so add to `lost`.
         lost.append(l)

输出正确的列表:

>>> news
[['1', 'C', 'c', '100'], ['1', 'D', 'd', '4500']]
>>> lost
[['2', 'X', 'x', '98'], ['2', 'Z', 'z', '276'], ['3', 'F', 'f', '76'], ['3', 'Y', 'y', '99']]
>>> changes
[['2', 'A', 'a', '3'], ['3', 'A', 'a', '54'], ['2', 'B', 'b', '302'], ['3', 'B', 'b', '65']]

推荐阅读