Python: how to find common values in three lists

前端 未结 3 484
情歌与酒
情歌与酒 2020-12-29 07:42

I try to find common list of values for three different lists:

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]

of course naturally I try to use t

相关标签:
3条回答
  • 2020-12-29 08:07

    For those still stumbling uppon this question, with numpy one can use:

    np.intersect1d(array1, array2)
    

    This works with lists as well as numpy arrays. It could be extended to more arrays with the help of functools.reduce, or it can simply be repeated for several arrays.

    from functools import reduce
    reduce(np.intersect1d, (array1, array2, array3))
    

    or

    new_array = np.intersect1d(array1, array2)
    np.intersect1d(new_array, array3)
    
    0 讨论(0)
  • 2020-12-29 08:13

    Use sets:

    >>> a = [1, 2, 3, 4]
    >>> b = [2, 3, 4, 5]
    >>> c = [3, 4, 5, 6]
    >>> set(a) & set(b) & set(c)
    {3, 4}
    

    Or as Jon suggested:

    >>> set(a).intersection(b, c)
    {3, 4}
    

    Using sets has the benefit that you don’t need to repeatedly iterate the original lists. Each list is iterated once to create the sets, and then the sets are intersected.

    The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a, so for longer list, this will be a lot less efficient.

    0 讨论(0)
  • 2020-12-29 08:18
    out = [x for x in a if x in b and x in c]
    

    is a quick and simple solution. This constructs a list out with entries from a, if those entries are in b and c.

    For larger lists, you want to look at the answer provided by @poke

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