简体   繁体   中英

Compare items on the same index on 2 lists

I have 2 lists: (the actual lists are longer)

list1 = ['ARHEL 7 FY2017 64-bit', u'7.2', 'BRHEL 7 FY2017 64-bit', u'7.3']

list2 = [(u'RHSA-2017:2796', u'6.7'), (u'RHSA-2017:2794', u'7.2'), (u'RHSA-2017:2793', u'7.3')]

How can I compare the second item numbers, ie 6.7 , 7.2 , 7.3 between the lists and if there is a match between the items in the 2 lists, like we have in list1 item 4 which is 7.3 and list2 third tuple item 2 which is also 7.3 ,

Then create a new list of tuples (like list 2 is constructed) taking the item that comes before the match to 7.3 which is 'BRHEL 7 FY2017 64-bit' and add it to the new tuple list

ie

list 3 = [('ARHEL 7 FY2017 64-bit', u'7.2'), ('BRHEL 7 FY2017 64-bit', u'7.3')]

What about using the following one-line solution

>>> list3 = [(list1[list1.index(v)-1],v) for (k,v) in filter(lambda el:el[1] in list1, list2)]
>>> list3
[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]


In details, first you get the filtered version of list2 , restricted so that it contains only values that list1 also contains

>>> list2_filtered = filter(lambda el:el[1] in list1, list2)

Then you retrieve list1 's elements which precedes each v of list2_filtered 's values

>>> list3 = [(list1[list1.index(v)-1],v) for (k,v) in list2_filtered]
>>> list3
[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]
list1 = ['ARHEL 7 FY2017 64-bit', u'7.2', 'BRHEL 7 FY2017 64-bit', u'7.3']
list2 = [(u'RHSA-2017:2796', u'6.7'), (u'RHSA-2017:2794', u'7.2'), (u'RHSA-2017:2793', u'7.3')]

result = []
for n,v in list2:
    if v in list1:
        idx = list1.index(v)
        if idx != 0: result.append((list1[idx-1], v))

print(result)

The output:

[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]

As you want :

taking the item that comes before the match

One line solution :

print([(list1[index-1],item) for index,item in enumerate(list1) for item1 in list2 if item==item1[1]])

output:

[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]

Detailed solution:

list_3=[]
for index,item in enumerate(list1):
    for item1 in list2:
        if item==item1[1]:
            list_3.append((list1[index-1],item))

print(list_3)

output:

[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]

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