Finding Common Values in Two Python Lists
In daily life, we often encounter the need to find common values between two arrays. This article provides several simple and practical methods on how to elegantly get common values between two arrays in Python.
1. Using the &
operator with sets
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1) & set(list2)
#{1, 3, 5, 7}
2. Using the intersection()
method with sets
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1).intersection(list2)
#{1, 3, 5, 7}
3. Brute-force checking if an element from the first list is in the second list
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
[element for element in list1 if element in list2]
# [1, 3, 5, 7]
4. Using set subtraction
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1) - (set(list1)-set(list2))
#{1, 3, 5, 7}
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/289.html
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。