判断一个数组的元素是否在另一个数组里
时间: 2023-12-18 21:06:05 浏览: 127
C语言中判断两数组中是否有相同的元素
可以使用循环和条件判断来判断一个数组的元素是否在另一个数组里。
Python代码示例:
```python
arr1 = [1, 2, 3, 4, 5]
arr2 = [3, 5, 7, 9]
for i in arr1:
if i in arr2:
print(i, "is in arr2")
else:
print(i, "is not in arr2")
```
输出:
```
1 is not in arr2
2 is not in arr2
3 is in arr2
4 is not in arr2
5 is in arr2
```
另外,还可以使用Python的set类型来判断两个数组是否有交集:
```python
arr1 = [1, 2, 3, 4, 5]
arr2 = [3, 5, 7, 9]
set1 = set(arr1)
set2 = set(arr2)
if set1.intersection(set2):
print("There are common elements in arr1 and arr2")
else:
print("There are no common elements in arr1 and arr2")
```
输出:
```
There are common elements in arr1 and arr2
```
阅读全文