Removing the lists from a list which are duplicated for some items

后端 未结 4 1552
面向向阳花
面向向阳花 2020-12-20 00:32

I\'m trying to remove the lists from a list which have same first and third items but only keeping the first one. Example list and output:

li=[ [2,4,5], [1,3         


        
4条回答
  •  悲哀的现实
    2020-12-20 01:14

    Use a set for storing the seen elements. That is faster:

    seen = set()
    res = []
    for entry in li:
        cond = (entry[0], entry[2])
        if cond not in seen:
            res.append(entry)
            seen.add(cond)
    
    
    [[2, 4, 5], [1, 3, 5]]
    

    ADDITION

    Also, the time spend on thinking about telling variables names is typically well spend. Often things first though of as throw-away solutions stick around much longer than anticipated.

提交回复
热议问题