簡體   English   中英

需要幫助來簡化一個程序,該程序查找一個數字在數組中出現的次數

[英]need help simplifying a program that finds how many times a number appears in an array

我已經弄清楚如何使用 .count() 來執行此操作,但是我想找到另一種方法來縮短代碼。

if check[0]==check[1]==check[2]:
  print('jackpot!')
  money = money+100
if check[0]!=check[1]!=check[2]:
  num1 = check.count(1)
  if num1 == 2:
    print('you've won £50')
    money = money+50
  else:
    print('youve lost')
    break
  num2 = check.count(2)
  if num2 == 2:
    print('you've won £50')
    money = money+50
  else:
    print('you've lost')
    break
  num3 = check.count(3)
 if num3 == 2:
    print('you've won £50')
    money = money+50
  else:
    print('you've lost')
    break

如果您只有 3 個數字並且需要檢查check[]列表中是否有 2 個相同的數字,那么這兩個中的任何一個都可以。 第一個是使用 for 循環迭代列表並使用 .count .count() function。第二個是僅使用if elif else語句,注意嵌套。 對於第一個,列表大小無關緊要,因為無論大小它都會迭代,但第二個僅適用於 3 個數字。

check = [1, 1, 3, 1 ,5, 6]

for i in check:
    if check.count(i) >= 3:
        print("jackpot!")
        exit()
    elif check.count(i) == 2:
        print("you have won 50")
        exit()
else:
    print("you have lost")

或者

check = [1, 2, 3]

if check[0] == check[1] == check[2]:
    print("jackpot!")
elif check[0] == check[1] or check[1] == check[2] or check[0] == check[2]:
    print("you have won 50")
else:
    print("you have lost")

暫無
暫無

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

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