Write a function named compare_list that takes two lists and returns True if they have at least one common element, and returns False otherwise.
时间: 2024-02-04 09:02:06 浏览: 31
Sure, here's the function:
```python
def compare_list(list1, list2):
"""
This function takes two lists as input and returns True if they have at least one common element, and False otherwise.
"""
for element in list1:
if element in list2:
return True
return False
```
You can use this function to compare two lists and check if they have at least one common element. For example:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
if compare_list(list1, list2):
print("The two lists have at least one common element.")
else:
print("The two lists do not have any common element.")
```
Output:
```
The two lists have at least one common element.
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)