Python:列表项的匹配列表

时间:2016-02-02 13:06:53

标签: python list list-comprehension

这里我需要将list1项目与第二个索引项目的list2进行比较,如果一个项目遗漏,那么我想在list1的错过项目索引处插入False

  

我的输入是

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

例外输出

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

我试过了:

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

请帮帮我。 提前谢谢....

2 个答案:

答案 0 :(得分:0)

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()

答案 1 :(得分:0)

如果你想忽略订单使用冻结集,将list1中的所有元素映射到frozensets以及list2的子列表中的所有第二个元素,请使用OrderedDict来保持顺序并找到两者之间的差异。

当您知道list1中不在list2中的内容时,您可以将OrderedDict压缩为原始列表,Ordereddict中任何与集合不同的键意味着您需要在该索引处添加False:< / p>

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)

输出:

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

frozenset适用于任何数量的元素而不仅仅是两个,反转子列表只适用于2,除非订单发生完全相反。