简体   繁体   中英

Python: Match list of list item

Here I need to compare list1 items with list2 of 2nd index items, if a item missed, then I want insert False at missed item index of list1.

My input is

list1 = [[1,2],[2,3],[3,4],[4,5]]
list2 = [[1,[3,2]], [3,[2,1]], [4,[5,4]]]

Excepted output is

result = [[3,[1,2]], [1,[2,3]], False, [4,[4,5]]]

I tried this:

list1 = [[1,2],[2,3],[3,4],[4,5]]
list2 = [[1,[3,2]], [3,[2,1]], [4,[5,4]]]

sss = []
for x in list1:
    sss.append([x for i in range(0, len(list2)) if set(x) == set(list2[i][1])])
print sss

Please Help me with this. Thanks in advance....

def list_lolwut(list1, list2):
    tmp = dict([(str(list(reversed(b))), [a, list(reversed(b))]) for a,b in list2])
    return [tmp.get(str(item), False) for item in list1]

import unittest

class Test(unittest.TestCase):
    def test1(self):
        list1 = [[1,2],[2,3],[3,4],[4,5]]
        list2 = [[1,[3,2]], [3,[2,1]], [4,[5,4]]]
        expected = [[3,[1,2]], [1,[2,3]], False, [4,[4,5]]]
        self.assertEqual(expected, list_lolwut(list1, list2))

unittest.main()

If you want to ignore order use a frozenset, map all elements in list1 to frozensets and all second elements from the sublists of list2, use an OrderedDict to keep the order and find the difference between the two.

When you know what is in list1 that is not in list2 you can zip the OrderedDict with the original list, any key from the Ordereddict that is in the difference of the sets means you need to add a False at that index:

from collections import OrderedDict
from itertools import chain

# keep the order from list1
od = OrderedDict.fromkeys(map(frozenset, list1))
# get what is in list1 that is not a second element from the sublists of list2
diff = set(od.keys() - map(frozenset, map(itemgetter(1), list2)))
# get the indexes that are different
inds = {ind for ind, (k, ele) in enumerate(zip(od, list1)) if k in diff}
# insert False at the correct indexes
list2[:] = chain(*([False] + [sub] if i in inds else [sub] for i, sub in enumerate(list2)))
print(list2)

Output:

[[1, [3, 2]], [3, [2, 1]], False, [4, [5, 4]]]

A frozenset will work for any amount of elements not just two, reversing the sublists would only work for 2 unless the order happend to be exactly reversed.

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