简体   繁体   English

Python:匹配列表项的列表

[英]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. 在这里,我需要将list1项与第二索引项的list2进行比较,如果错过了一项,那么我想在list1的错过项索引中插入False

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. 如果要忽略使用冻结集的订单,请将list1中的所有元素映射到冻结集,并将第二个元素映射到list2的子列表中,请使用OrderedDict保持订单并查找两者之间的差异。

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: 当您知道list1中的内容而不是list2中的内容时,可以用原始列表压缩OrderedDict,Ordereddict中任何键集不同的键都意味着您需要在该索引处添加False:

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. frozenset适用于任意数量的元素,而不仅仅是两个,反转子列表仅适用于2个元素,除非顺序恰好恰好相反。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM