簡體   English   中英

如何檢查python中元素列表中的空元素

[英]How to check for a empty element within a list of elements in python

舉例來說,我有一個包含如下數據的列表列表:

    customer1 = ['Dan','24','red']
    customer2 = ['Bob',' ','Blue']
    customerlist = [customer1, customer2]

如果這些元素之一為空,我想運行一行代碼來運行一個函數。 例如這樣的事情:

    for c in customerlist:
        if not in c:
            ***RUN CODE***
        else:
            print('Customer Complete')

這樣,如果客戶缺少數據,我可以運行一些代碼。

謝謝您的幫助!

您可以使用in檢查' '

for c in customerlist:
    if ' ' in c:
        RUN CODE
    else:
        print('Customer Complete')

取而代之的是:

    if not in c:

你要這個:

    for val in c:
        if not val.strip():

它基本上檢查是否有任何字符串為空(空字符串在 Python 中是“falsey”)。 剝離首先檢測僅包含空格的字符串。

Guy 和 John 給出的兩個答案都是正確的,但也許您會對研究對象感興趣:

class Customer:
    def __init__(self, name, age = None, color = None):
        self.name = name
        self.age = age if age else age_function_generator()
        self.color = color if color else color_function_generator()

要創建客戶,只需執行以下操作:

c1 = Customer(name = "Dan", age = 24, color = "red")
c2 = Customer(name = "Bob", color = "Blue")

c2的情況下,將調用函數age_function_generator() (此處未定義)。 要訪問客戶對象的屬性,可以這樣做:

print(c1.name, c1.age, c1.color)

您可以使用 Python 正則表達式來搜索列表中的空白條目。 正則表達式是定義模式的字符序列。 有關 Python 正則表達式的更多信息,請訪問: w3school 鏈接Google Developer 鏈接

請替換以下代碼

for c in customerlist:
        if not in c:

使用以下代碼:

for i in range(len(customerlist)):
    for j in range(len(customer1)):
        emptylist = re.findall('\s*', customerlist[i][j])

不要忘記在代碼開頭包含 'import re' 以導入 Python re 模塊

完整代碼:

import re
customer1 = ['Dan','24','red']
customer2 = ['Bob',' ','Blue', ' ']
customerlist = [customer1, customer2]

for i in range(len(customerlist)):
    for j in range(len(customer1)):
        emptylist = re.findall('\s*', customerlist[i][j])
if(len(emptylist) == 0):
    print('There are no blank entries')
else:
    print('There are blank entries')
    #code goes here to do something

輸出:

There are blank entries

在代碼中:

emptylist = re.findall('\s*', customerlist[i][j])

re.findall() 搜索零個或多個空白字符 (\\s) 實例 (*),以 customerlist 為迭代列表。 customerlist[i][j] 因為它是一個列表列表。

暫無
暫無

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

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