簡體   English   中英

如何獲取輸入,將其添加到列表中,並使用循環和 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 loops, if, elif, else statement, 3 employees etc..}

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}。 然后我打印了列表以進行可視化。

在我通過一個帶有變量checkfor loop訪問列表 { list_sal } 中的元素之后,該變量檢查在 count() function 的幫助下查找元素在列表中重復的次數,其中,如果大於一個,則打印“提供相同的薪水”或打印“唯一薪水”..

您可能想知道為什么我使用了 2 個 break 語句。它們用於中斷進一步的迭代,因為在第一次迭代中滿足if or else條件。 如果您嘗試刪除 break 語句,打印 function 將在列表中出現相同薪水的次數。

希望我對你有所幫助.. 我也是編程新手,但我喜歡它並且經常練習。 繼續打磨,努力工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM