简体   繁体   English

比较列表中的子项

[英]Comparing sub items from a list of lists

I,ve 2 lists: 我有2个清单:

l = [['red','a1',1],['red','a2',1],['blue','a3',1],['yellow','a4',1]]

and

k = [['red','a2',1],['blue','a3',1],['yellow','a4',1]]

so I want to return something like this: 所以我想返回这样的东西:

result = [0, 1, 1, 1]

Sorry I´ve to practice list comprehension a little more!! 抱歉,我还要多练习列表理解!!

my function: 我的功能:

def vectors(doc1,doc2,consulta):
    res=[]
    r = doc1 + doc2 + consulta
    for e in r:
        for i in doc1:
            if i[0] == e[0]:
                i[2] = i[2] + 1
        else:
            i[2] = 0
    return res.append(i[2])

The order doesn´t matter, the important thing is the comparison. 顺序无关紧要,重要的是比较。

Best Regards! 最好的祝福!

Inefficient but easy: 低效但容易:

result = [x in k for x in l]

Efficient (for large k ) but slightly more complicated: 高效(对于大k ),但稍微复杂一点:

kset = set(tuple(x) for x in k)
result = [tuple(x) in kset for x in l]

Check this: 检查一下:

>>> result = [1 if li in k else 0 for li in l]
>>> result
[0, 1, 1, 1]

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

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