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.
时间: 2023-12-06 22:39:44 浏览: 93
Java比较两个List的值是否相等的方法
Here's a Python function named `compare_list` that takes two lists and returns `True` if they have at least one common element, and returns `False` otherwise:
```python
def compare_list(list1, list2):
for item in list1:
if item in list2:
return True
return False
```
In this function, we loop through each item in `list1`, and check if it exists in `list2`. If we find a common element, we immediately return `True`. If we've looped through all of `list1` without finding a common element, we return `False`.
You can call this function with your own lists as follows:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
result1 = compare_list(list1, list2)
print(result1) # False
list3 = [1, 2, 3, 4, 5]
list4 = [5, 6, 7, 8, 9]
result2 = compare_list(list3, list4)
print(result2) # True
```
阅读全文