我目前正在制作一个数独游戏,因为验证背后的逻辑编写起来非常有趣,而且有很多方法可以做到这一点。
我的问题很简单。 python中是否有任何函数可以检查一个值是否多次出现在列表中?
我编写了一个小函数来执行此操作,并且可以正常工作:
def IsRepeated(list):
overlap = False
for index, val in enumerate(list):
for step in range(index+1, len(list)):
if val == list[step]:
overlap = True
break
if overlap:
break
return overlap
输入是一个列表,如 a = [1,2,3,4,5,6]
这非常有效,但我想确保没有其他更好的方法来做到这一点,因为通常有。
最佳答案
使用 Python 控制台的示例:
>>> a=[1,2,3,4,5,6,6]
>>> set(a)
{1, 2, 3, 4, 5, 6}
>>> len(set(a))
6
>>> len(a)
7
>>> if len(set(a)) != len(a):
... print("Yes, there is some value present in a list more than once.")
...
Yes, there is some value present in a list more than once.
关于python - 检测列表中的相同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55079174/