如何获取输入,将其添加到列表中,并使用循环和 if elif else 语句来检查是否有任何两个值相同?

How do I take an input, add it to a list, and use loops and if elif else statements to check if any two values are the same?

我正在尝试制作一个简单的程序,该程序使用 for 循环、if-elif-else 语句和输入来获取三个“员工”的薪水并将它们进行比较以查看 A 是否具有相同的薪水。如果没有人有相同的薪水,则为 B。到目前为止,这就是我得到的,但我尝试过的两种策略都没有成功,我不明白为什么 :(。感谢所有帮助,请原谅我,因为我还是编码新手,而且我是尝试通过这些练习自学。谢谢!

salarylist = [] 
salarylist = list(map(int, salarylist))


maxLengthList = 3
while len(salarylist) < maxLengthList:
    salary_of_employee = int(input("Enter your salary: "))
    salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
    print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
    print('non of the salaries are the same.')

    
############################################################################   
    
    
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]

if empOne == salarylist[0]:
    print("these are the same salary.")
elif empTwo == salarylist[1]:
    print('these are the same salary')
elif empThree == salarylist[2]:
    print('these are the same salary')
else:
    print('non of the salaries are the same.')

当你有薪资列表时,从该列表中创建一个集合并比较长度,如果长度相同则薪资将是唯一的,否则将至少有一个共同的薪资


lst2 = set(salarylist)

if(len(lst2) == len(salarylist)):
  print("Non of the salaries are the same.")
else:
  print("Same salaries found")

通过集合和检查列表中元素的计数来找到相同的薪水循环,如果大于一,则重复。

for sal in lst2:
  if(salarylist.count(sal) > 1):
    print("Duplicate here")

我试过 运行 你的代码,它给出了一个可怕的错误。 我很清楚你的愿望。你的大部分逻辑都不符合它。 所以我决定根据您的要求重新编码所有内容{for 循环、if、elif、else 语句、3 名员工等。}

MAX_LEN = 3
COUNTER = 1 
LIST_SAL = []
while MAX_LEN >= COUNTER:
    ASK_SAL = int(input('Enter your salary :'))
    LIST_SAL.append(ASK_SAL)
    COUNTER+=1
print(LIST_SAL)
for check in LIST_SAL:
    if LIST_SAL.count(check)>1:
        print('Same salaries presented in the list')
        break
    else:
        print('Salaries of employees are unique!')
        break 

好吧.. 我创建了一个变量 max_len = 3,它是员工总数,然后我将变量 COUNTER 初始化为 1,以便它在 while 循环中迭代并每次递增 1。 此后,名为 ask_sal 的变量向用户询问薪水 {3 次},并将每个输入附加到 LIST_SAL 变量 {a list}。然后我打印了列表以供可视化。

在我通过 for loop 和变量 check 访问列表 {list_sal} 中的元素之后,它查找元素在列表中重复的次数在 count() 函数的帮助下,如果大于一个,则打印“提供的薪水相同”,否则打印“唯一的薪水”..

您可能想知道为什么我使用了 2 个 break 语句.. 好吧,它们用于中断进一步的迭代,因为在第一次迭代中满足了 if or else 条件。 如果您尝试删除 break 语句,打印函数将工作相同薪水在列表中出现的次数。

希望我能帮到你。我也是,一个编程新手,但我喜欢它并且经常练习。 继续打磨和努力