我只想从for循环Python中得到一个答案

2024-04-26 01:41:00 发布

您现在位置:Python中文网/ 问答频道 /正文

任务:

Write a program that will list at least 6 numbers for the customer. The program must process the received list and write down on each line whether the current number has been repeated before. If repeated, write "YES", if not - "NO". for example:

Step 1: The user enters at least 6 numbers that are stored in the array, say included [1, 2, 1, 1, 4, 2]

Step 2: The program will process the received list and display the answers on the following screen:

NO 
NO 
YES 
YES 
NO 
YES

我的代码:

x = []
y = []
for i in range (6):
   i = int(input("Enter a number: "))
   x.append(i)

for z in range(len(x)):
     for j in range (z + 1,len(x)):
        if x[z] == x[j]:
            y.append("YES")
        else:
             y.append("NO")         
        if "YES" in y:
           print("YES")
           y.clear()
        else:
           print("NO")
           y.clear()

我创建y只是为了一个实验,如果你想用的话,不要用它。我只想检查一个元素是否与另一个元素相同,如果是的话,只给我一个是不是不是不是不是不是不是不是,是不是或者类似的东西,如果它们不相同,就给我一个不是


Tags: thenoinforifthatrangeprogram
1条回答
网友
1楼 · 发布于 2024-04-26 01:41:00

使用切片检查每个元素是否位于列表的前一部分。您可以使用内置的in操作符来测试是否存在重复,而不是使用嵌套循环

for i, num in enumerate(x):
    if num in x[:i]:
        print("YES")
    else:
        print("NO")

相关问题 更多 >