重复元素判定。编写一个函数,接受列表作为参数,如果一个元素在列表中出现了不止一次,则返回True,但不要改变原来列表的值。同时编写调用这个函数和测试结果的程序。
时间: 2024-03-31 07:14:53 浏览: 89
好的,我明白了。下面是代码及测试程序:
```
def check_duplicate(lst):
"""
判断列表中是否存在重复元素
参数:
lst:列表
返回值:
存在重复元素则返回True,否则返回False
"""
if len(lst) != len(set(lst)):
return True
else:
return False
# 调用函数并测试结果
lst = [1, 2, 3, 4, 5]
print(check_duplicate(lst)) # False
lst = [1, 2, 2, 3, 4, 5]
print(check_duplicate(lst)) # True
lst = [1, 2, 3, 3, 3, 3]
print(check_duplicate(lst)) # True
# 原列表没有变化
lst = [1, 2, 3, 4, 5]
print(lst) # [1, 2, 3, 4, 5]
```
这里定义了一个 `check_duplicate` 函数,它接受列表作为参数,判断其中是否存在重复元素,如果存在则返回 True,否则返回 False。需要注意的是,这个函数并不会改变原来列表的值。
接下来,我们调用这个函数并测试结果。第一个列表中不存在重复元素,所以应该返回 False;第二个列表中有两个 2,应该返回 True;第三个列表中有三个 3,应该返回 True。
最后,我们再次输出原来的列表,确保它没有被改变。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)