简体   繁体   English

根据另一个列表列表从列表列表中选择元素

[英]Select elements from a list of lists based on another list of lists

I have two lists of lists that will always have the same lengths.我有两个列表的列表,它们总是具有相同的长度。

l1 = [[0, 1, 2, 2, 0, 1, 2], [0, 1, 0, 0, 0], [0, 1, 2, 0, 0]]
l2 = [[0,(1,'a','b'), (1,'a','b'), (1,'a','b'), 0, (3, 'x','y'), 0], [0, (2,'c','d'), 0, 0, 0], [0, (3, 'e','f'), 0, 0, 0]]

What I want is to return the non 0 elements of l2 only if the quantity of identical elements much the sequence of 1-2s from l1 (or just 1s).我想要的是仅当相同元素的数量与 l1 中的 1-2s 序列(或仅 1s)相同时才返回 l2 的非 0 元素。 In this case for example, I would like it to return just例如,在这种情况下,我希望它只返回

out = [[(1,'a','b'), (1,'a','b'), (1,'a','b')], [(2,'c','d')], []]

because there are three identical tuples and a sequence of 1-2-2, while for (3, 'e','f'), there is only on but there is a sequence of 1-2 (so it should have been (3,'e','f'),(3, 'e','f') instead in l2.因为有三个相同的元组和一个 1-2-2 的序列,而对于 (3, 'e','f'),只有 on 但有一个 1-2 的序列(所以它应该是( 3,'e','f'),(3, 'e','f') 而不是在 l2 中。

What I have been trying to do is use Counter to count the occurrences of non '0' elements, but when counting 1 and 2s it does not differentiate between sequences, so I cannot do a comparison我一直在尝试做的是使用 Counter 来计算非 '0' 元素的出现次数,但是在计算 1 和 2s 时它不区分序列,因此我无法进行比较

for x, y in zip(l1,l2):
    print(Counter(x),Counter(y))

returns返回

Counter({2: 3, 0: 2, 1: 2}) Counter({0: 3, (1, 'a', 'b'): 3, (3, 'x', 'y'): 1})
Counter({0: 4, 1: 1}) Counter({0: 3, (2, 'c', 'd'): 2})
Counter({0: 5}) Counter({0: 4, (3, 'e', 'f'): 1})

where there is no way to no what the count of 1 and 2 correspond to.没有办法知道 1 和 2 的计数对应什么。

Any help on how to go about doing this?有关如何执行此操作的任何帮助?

Some input-expected output examples:一些输入预期输出示例:

l1 = [[0,1,2,0], [0,1]]
l2 = [[0, (1,'a','b'), (1,'a','b'), 0],[(2,'a','b'),(2,'a','b')]]
out = [[(1,'a','b'), (1,'a','b')],[]]

l1 = [[2,2,2], [1,2]]
l2 = [[(1,'a','b'), (1,'a','b'), (1,'a','b')],[(2,'a','b'),(2,'a','b')]]
out = [[(1,'a','b'), (1,'a','b'), (1,'a','b')],[(2,'a','b'),(2,'a','b')]]

l1 = [[0,1], [0,0]]
l2 = [[0, (3, 'x','y')],[0,0]]
out = [[(3, 'x','y')],[]]

Doesn't this just gives the desired output.这不只是提供了所需的输出。

op =[]
def ml(l1, l2):
    for x,y in zip(l1,l2):
        sl =[] 
        for a,b in zip(x,y):
            if a:
                sl.append(b)
        op.append(sl)
    return op

print(ml(l1, l2))

Please clarify if output is not as desired.如果输出不符合要求,请说明。

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

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