簡體   English   中英

如何獲得僅打印一個輸出的代碼?

[英]How do I get my code to only print one output?

本質上,我正在嘗試創建一個讀取數組和數字的函數。 如果數字在數組中,則應返回True ,否則返回False 但是,我發現對於數組中的每個元素都有一個TrueFalse當我只需要一個TrueFalse時,代碼會單獨檢查所有內容; 是數組中的數字嗎?

def is_it_there(arr, k):
    for x in arr:
        if x == k:
            print(True)
        else:
            print(False)

is_it_there([8,5,2,234,426,7,11],11)

就像我之前說過的,只期望一個True,但是檢查了每個項目,所以它是False, False, False, False, False, False, True

只是

if k in arr:
   print(True)
else:
   print(False)

或者,更簡單

print(k in arr)

您可以這樣重構代碼:

def is_it_there(arr, k):
    for x in arr:
        if x == k
            return True
    return False

print(is_it_there([8,5,2,234,426,7,11],11))

如果您在列表中的任何位置找到該項目,請打印True並立即退出功能。

如果一直到列表末尾都沒有找到它,則僅打印False

def is_it_there(arr, k):
    for x in arr:
        if x == k:
            # print True and terminate the function
            print(True)
            return
    # if we made it all the way through the loop, we didn't find it
    print(False)

但是,“ in”運算符已經可以滿足您的要求:

if value in mylist:
    print 'True'
else:
    print 'False'

問題源於事實,因為您在循環遍歷元素時不斷對其進行檢查。 因此,代碼將不斷檢查該元素是否存在。 因此,您將最終每次都打印一條語句。 Python提供了一種完美的方法來實現這一目標

def is_it_there(arr, k):
    if k in arr:
       print(True)
    else:
       print(False)

is_it_there([8,5,2,234,426,7,11],11)

每次在循環中進行測試時,您都在打印結果。 嘗試將每個測試回合的結果記錄在一個列表中,並測試結果列表中是否有任何“ True”值。

代碼示例:

def is_it_there(arr, k):
    result = list()
    for x in arr:
        if x == k:
            result.append(True)
        else:
            result.append(False)
    if True in  result:
        print(True)
    else:
        print(False)
is_it_there([8,5,2,234,426,7,11],11)

暫無
暫無

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

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