python 如果整数重复,则打印true,否则打印false

new9mtju  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(171)

我想写一个程序来询问列表的长度和它的整数元素,但是从整数列表中,程序需要找出是否有重复的整数,如果有:如果发现重复,则打印“True”,否则打印“False”。
下面应该是示例输出:

Enter list length: 3
Enter element 1: 100
Enter element 2: 2312
Enter element 3: 12312312
Has duplicate?: False

emp = [] 
listLen = int(input("Enter the number of elements: "))
num = 1

for i in range(listLen):
  e = int(input("Enter element %d: " % num))
  num += 1

(this第^部分仅用于询问输入)

for i in range(e):
  if e.count(item) > 1:
    print("Has duplicate?: True")
  else:
    print("Has duplicate?: False")

但我一直收到错误:

AttributeError Traceback (most recent call last) <ipython-input-7-d4356802d6f7> in <module> 8 9 for i in range(e): ---> 10 if e.count(item) > 1: 11 print("Has duplicate? True") 12 else: AttributeError: 'int' object has no attribute 'count' –
cetgtptt

cetgtptt1#

当你应用count函数时,它应该像list_name.count(the_value_to_count)
但是当你在做e.count(item)的时候,e基本上是一个数字,而不是列表,集合,元组
你可以像这样使用count函数。

emp = [] 
listLen = int(input("Enter the number of elements: "))
num = 1

for i in range(listLen):
  e = int(input("Enter element %d: " % num))
  num += 1
  emp.append(e)
  

for i in set(emp):
  #emp is a list. and i is the number. for which we have to count.    
  if emp.count(i) > 1:
    print(str(i)+" Has duplicate?: True")
  else:
    print(str(i)+" Has duplicate?: False")
    • 输出:**
Enter the number of elements: 6
Enter element 1: 99
Enter element 2: 42
Enter element 3: 63
Enter element 4: 42
Enter element 5: 56
Enter element 6: 99
56 Has duplicate?: False
42 Has duplicate?: True
99 Has duplicate?: True
63 Has duplicate?: False
    • 注意**list不按顺序,因为我在for循环中应用了set
    • 更新答复。**
    • 如果您只想检查列表是否包含重复项。**

使用计数器

from collections import Counter
emp = [] 
listLen = int(input("Enter the number of elements: "))
num = 1

for i in range(listLen):
  e = int(input("Enter element %d: " % num))
  num += 1
  emp.append(e)
  
a=Counter(emp)
if max(a.values()) > 1:
    print(" List Has duplicate?: True")
else:
    print(" List Has duplicate?: False")
    • 输出:**
Enter the number of elements: 5
Enter element 1: 2
Enter element 2: 3
Enter element 3: 1
Enter element 4: 2
Enter element 5: 5
List Has duplicate?: True

相关问题