python - 在 python 中从函数返回值时遇到问题
问题描述
我下面的代码吐出 TRUE 虽然没有重复。不幸的是,我受到了不允许我更改主要功能的约束。任何人都可以帮助我了解如何确保我的功能返回到主要功能?我在其他地方遇到了这个问题,因此将不胜感激答案背后的推理。
ONE_TEN =[12, 20, 10, 14, 54, 16, 75, 38, 79, 103] #this is test run 2
#j. Demonstrate testing if the list contains duplicates.
print("The list has duplicates: ", hasDuplicate(ONE_TEN))
def hasDuplicate(data:list)->bool:
'''Return true if the list contains duplicate elements
(which need not be adjacent)'''
unique = set(data)
unique = list(unique)
fact = unique != data
return(fact)
if __name__ == "__main__":
main() ```
解决方案
你没有做正确的比较。简单的调试显示了问题:只需打印两个列表:
unique = set(data)
unique = list(unique)
print(unique, '\n', data)
输出:
[38, 103, 10, 75, 12, 14, 79, 16, 20, 54]
[12, 20, 10, 14, 54, 16, 75, 38, 79, 103]
相反,比较长度:您的整个功能可以很简单
return len(data) != len(set(data))
集合是元素的集合;Python 会以它认为方便的任何顺序存储元素。因此,当您将列表转换为集合时,顺序可能会发生变化。集合的定义没有顺序——但 Python 确实定义了一个迭代器,因此您可以循环遍历元素。
当你从一个集合中创建一个列表时,你会得到 Python 喜欢使用的任何顺序,通常是一些明显无意义的排列,这些排列是由使用的散列函数产生的。当你从一个集合中创建一个列表时,Python 会简单地遍历这个集合,因此你会在列表中获得基于集合的顺序。没有理由期望这个顺序与元素的来源有关。