簡體   English   中英

python如何檢查列表不包含任何值

[英]python how to check list does't contain any value

考慮這個簡單的功能

def foo(l=[]):
    if not l:  print "List is empty"
    else : print "List is not empty"

現在讓我們打電話給foo

x=[]
foo(x)
#List is empty

foo('')
#List is empty

但如果x = [''],則列表不被視為空!

x=['']
foo(x)
#List is not empty

問題 -

  1. 為什么空值列表不被視為空? (在變量的情況下,它被認為是空的,例如)

     x='' if x:print 'not empty!!' else: print 'empty' 
  2. 如何修改函數foo(),以便在所有這些情況下列表將被視為空: x=[]x=['']x=['', '']

使用內置的any()

def foo(l=[]):
    if any(l):
        print 'List is not empty'
    else:
        print 'List is empty'

foo([''])
# List is empty

在您的示例中,列表實際為空的唯一情況是方括號中沒有任何內容。 在其他示例中,您有包含各種數量的空字符串的列表。 這些是完全不同的(在我能想到的所有語言中,情況都是如此)。

首先:即使是空字符串也是字符串。 包含空字符串的列表仍包含元素。

雖然a=''為空且len = 0,但無論列表如何,它仍然包含一個元素,例如, mylist = [a]mylist = ['']相同,但它可能更清楚。 a作為元素並忽略內容。

要檢查列表的元素是否為空,請迭代它們。

def isEmpty(li=[]):
  for elem in li:
    if len(elem) > 0: return false
  return true

您可以使用函數foo的遞歸調用來處理嵌套列表。

def foo(l=[]):
    if type(l)==list:
        return any([foo(x) for x in l])
    else:
        return bool(l)

要回答關於為什么空值列表不被視為空的第一個問題,那是因為它確實包含某些內容,即使這些內容本身是空的。 把它想象成一盒空盒子。

下面的代碼顯示了一種修改函數foo()以執行所需操作(並測試它)的方法。 您對空列表的概念設計出人意料的難度很大,部分原因在於它與語言本身認為空洞的內容背道而馳。 正如您所看到的,根據您的定義確定列表是否為“空”的所有邏輯已被移動到一個名為empty_list()的單獨函數中,因為這可能與foo()的其余部分幾乎沒有關系。去完成。 它不是太復雜,如果沒有別的東西可以為你提供一個良好的起點。

此外,如果傳遞的參數不是任何類型的列表或者是列表但不包含其他列表或字符串,那么您沒有說它應該做什么,因此寫入它會引發TypeError異常 -類似於大多數內置Python函數響應的方式。 下面是示例代碼及其測試輸出:

try:
    string_type = basestring
except NameError: # probably Python 3.x
    string_type = str

class _NULL(object):  # unique marker object
    def __repr__(self): return '<nothing>'
_NULL = _NULL()

def empty_list(arg=_NULL):
    arg = arg if arg is not _NULL else []
    if not isinstance(arg, (list, string_type)):
        raise TypeError
    elif isinstance(arg, string_type):
        return not len(arg)
    else:
        return len(arg) == 0 or all(empty_list(e) for e in arg)

def foo(list_=None):
    if list_ is None or empty_list(list_):
        print 'list is empty'
    else:
        print 'list is not empty'

testcases = [
    _NULL,
    [],
    [''],
    ['', ''],
    ['', ['']],
    ['abc'],
    ['', 'abc'],
    [False],
    [None],
    [0],
    [0.0],
    [0L],
    [0j],
    [42],
    [{}],
    [{'':0}],
    [{'a':1}],
    False,
    None,
    0,
    0.0,
    0L,
    0j,
    42,
    {},
    {'':0},
    {'a':1},
]

for arg in testcases:
    call = 'foo( {!r:s} ) ->'.format(arg)
    print '{!s:>20s}'.format(call),
    try:
        foo() if arg is _NULL else foo(arg)
    except TypeError:
        print 'illegal argument exception'

這是使用Python 2.7生成的輸出:

 foo( <nothing> ) -> list is empty
        foo( [] ) -> list is empty
      foo( [''] ) -> list is empty
  foo( ['', ''] ) -> list is empty
foo( ['', ['']] ) -> list is empty
   foo( ['abc'] ) -> list is not empty
foo( ['', 'abc'] ) -> list is not empty
   foo( [False] ) -> illegal argument exception
    foo( [None] ) -> illegal argument exception
       foo( [0] ) -> illegal argument exception
     foo( [0.0] ) -> illegal argument exception
      foo( [0L] ) -> illegal argument exception
      foo( [0j] ) -> illegal argument exception
      foo( [42] ) -> illegal argument exception
      foo( [{}] ) -> illegal argument exception
 foo( [{'': 0}] ) -> illegal argument exception
foo( [{'a': 1}] ) -> illegal argument exception
     foo( False ) -> illegal argument exception
      foo( None ) -> list is empty
         foo( 0 ) -> illegal argument exception
       foo( 0.0 ) -> illegal argument exception
        foo( 0L ) -> illegal argument exception
        foo( 0j ) -> illegal argument exception
        foo( 42 ) -> illegal argument exception
        foo( {} ) -> illegal argument exception
   foo( {'': 0} ) -> illegal argument exception
  foo( {'a': 1} ) -> illegal argument exception

列表['']確實不是空的。 它包含一個空字符串。 字符串為空,列表不是 如果要查找這些列表,請檢查列表是否為空,如果不是,請檢查每個條目是否為“”。

暫無
暫無

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

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