Python – 直到遇到 False 元素為止的值


Python 是一種常用的程式語言,用於各種目的,例如 Web 開發、資料科學、機器學習以及執行各種不同的自動化任務。迴圈遍歷列表、元組或迭代器等集合的專案直到滿足特定條件,這經常是必要的。本文將使用相關的程式碼片段和示例,探討幾種遍歷資料直到找到 False 元素的方法。到文章結尾,您將牢固掌握如何在 Python 程式中整合這一點。

理解問題:讓我們考慮一種情況,我們需要處理資料集合中的每個成員,直到遇到 False 條件。該集合可以是任何可迭代的,例如列表、元組或其他。一旦我們遇到第一個 False 條目,我們就想停止迭代,並執行某些操作或返回提取的資料。

使用迴圈方法

使用 for 迴圈是一種處理此問題的簡單方法。當我們迴圈遍歷它時,會檢查集合中的每個條目,並且一旦發現 False 值,迴圈就會中斷。讓我們來看一個例子來更好地理解它

示例

def check_for_false_element(collection): # The function check_for_false_element is given the data as input 
    result = [] # A new empty list is created
    for element in collection: # It checks each element in the input using the for loop
        if not element: # If element evaluates to false then the loop will break and the function returns the collected elements up to that point
            break
        result.append(element)
    return result

# Example 
my_list = [2, 4, 6, 0, 8, 10] # Input of list is given
final_list = check_for_false_element(my_list) # The function is run
print(final_list)  # The output is displayed up to the correct elements

輸出

上述示例的輸出如下所示

[2, 4, 6] 

使用 Itertools

Python 包 Itertools 提供了強大的工具來處理迭代器。`takewhile` 函式就是這樣一種工具,它返回迭代器中的專案,直到滿足預定的條件。它可以幫助我們獲得想要的結果。讓我們來看一個例子來更好地理解它

示例

from itertools import takewhile # Do not forget to import itertools or else error might occur

def check_for_false_element(collection): # The function check_for_false_element is given the data as input
    return list(takewhile(bool, collection)) # 2 arguments are provided to the function takewhile- bool and the data to check and then the data is again converted into a list

# Example 
my_tuple = (True, True, True, True, False, True)  # Input of list is given
result_list = check_for_false_element(my_tuple) # The function check_for_false_element is run 
print(result_list)

輸出

上述示例的輸出如下所示

[True, True, True, True] 

列表推導式

Python 中的列表推導式提供了一種清晰易懂的方法,可以根據現有列表建立新列表。為了達到我們的目的,我們可以使用列表推導式。讓我們來看一個例子來更好地理解它

示例

def check_for_false_element(collection): # The function check_for_false_element is given the data as input
    return [element for element in collection if element] # Each element in the list is checked and once the false element is found the checking stops and the correct elements are returned

# Example 
my_list = [10, 20, 30, 40, 0, 50] # Input of list is given
result_list = check_for_false_element(my_list) # The function check_for_false_element is run 
print(result_list) 

輸出

上述示例的輸出如下所示

[10, 20, 30, 40, 50] 

生成器函式

可以使用生成器函式輕鬆建立迭代器。可以建立一個生成器函式,該函式從集合中提取元素,直到滿足 False 條件。讓我們來看一個例子來更好地理解它

示例

def check_for_false_element(collection): # The function check_for_false_element is given the data as input
    for element in collection: # Each element in the lsit is checked until the false element is found
        if not element:
            return # Once the false element is found it returns back 
        yield element

# Example 
my_list = [True, True, False, True, False, True] # Input of list is given
result_list = list(check_for_false_element(my_list)) # The function check_for_false_element is run 
print(result_list) 

輸出

上述示例的輸出如下所示

[True, True] 

While 迴圈和迭代器

While 迴圈可以與迭代器結合使用以獲得所需的輸出。讓我們來看一個例子來更好地理解它

示例

def check_for_false_element(collection): # The function check_for_false_element is given the data as input
    result = [] # A new list is created for the correct elements
    iterator = iter(collection) 
    while True:
        try:
            element = next(iterator) # We fetch the next element from the iterator using `next` function
            if not element:
                break
            result.append(element)
        except StopIteration: #stopiteration is used when the iterator is exhausted
            break # If the value is found false then loop is broken
    return result

# Example 
my_tuple = (1, 3, 5, 0, 7, 9)# Input of list is given
result_list = check_for_false_element(my_tuple) # The function check_for_false_element is run
print(result_list) 

輸出

上述示例的輸出如下所示

[1, 3, 5] 

結論

在這篇文章中,我們探討了在 Python 中處理資料直到找到 False 元素的各種方法。我們介紹了列表推導式、itertools 包中的 `takewhile` 函式以及 for 迴圈。您可以根據您的具體用例和編碼風格選擇最符合您需求的策略。

Python 的適應性和廣泛的工具集使開發人員能夠有效地處理各種情況。理解這些方法可以幫助您建立更可靠的 Python 應用程式並更有效地處理集合。

更新於:2023年8月1日

76 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告