How to find common elements in list of lists?

后端 未结 7 1154
無奈伤痛
無奈伤痛 2020-11-27 18:13

I\'m trying to figure out how to compare an n number of lists to find the common elements. For example:

p=[ [1,2,3],
    [1,9,9],
      ..
      ..
    [1,2         


        
相关标签:
7条回答
  • 2020-11-27 18:50

    A simple solution (one-line) is:

    set.intersection(*[set(list) for list in p])
    
    0 讨论(0)
  • 2020-11-27 18:50
    p=[ [1,2,3],
        [1,9,9],
        [1,2,4]]
    
    ans = [ele[0] for ele in zip(*p) if len(set(ele)) == 1]
    

    Result:

    >>> ans
    [1]
    
    0 讨论(0)
  • 2020-11-27 18:56

    You are looking for the set intersection of all the sublists, and the data type you should use for set operations is a set:

    result = set(p[0])
    for s in p[1:]:
        result.intersection_update(s)
    print result
    
    0 讨论(0)
  • 2020-11-27 19:02
    reduce(lambda x, y: x & y, (set(i) for i in p))
    
    0 讨论(0)
  • 2020-11-27 19:06

    Why not just:

    set.intersection(*map(set, p))
    

    Result:

    set([1])
    

    Or like this:

    ip = iter(p)
    s = set(next(ip))
    s.intersection(*ip)
    

    Result:

    set([1])
    

    edit:

    copied from console:

    >>> p = [[1,2,3], [1,9,9], [1,2,4]]
    >>> set.intersection(*map(set, p))
    set([1])
    >>> ip = iter(p)
    >>> s = set(next(ip))
    >>> s.intersection(*ip)
    set([1])
    
    0 讨论(0)
  • 2020-11-27 19:07

    You are looking for the set intersection of all the sublists, and the data type you should use for set operations is a set:

    result = set(p[0])  
    for s in p[1:]:
       result.intersection_update(s)
    print result
    

    However, there is a limitation of 10 lists in a list. Anything bigger causes 'result' list to be out of order. Assuming you've made 'result' into a list by list(result).

    Make sure you result.sort() to ensure it's ordered if you depend on it to be that way.

    0 讨论(0)
提交回复
热议问题