Python:列表项的匹配列表

2024-05-19 10:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

这里我需要将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]]]

我试过这个:

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

请帮帮我。 提前谢谢。。。。你知道吗


Tags: infalseforinputoutputismyrange
2条回答
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()

如果要忽略顺序,请使用frozenset,将list1中的所有元素映射到frozensets,并将list2的子列表中的所有第二个元素映射到frozensets,使用OrderedDict保持顺序并查找两者之间的差异。你知道吗

当您知道列表1中的内容不在列表2中时,您可以使用原始列表压缩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)

输出:

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

一个frozenset将适用于任何数量的元素,而不仅仅是两个,反转子列表只适用于2,除非顺序恰好相反。你知道吗

相关问题 更多 >

    热门问题