Um Ihre erste Frage, warum eine Liste leerer Werte zu beantworten nicht leer betrachtet, ist es, weil es etwas tut, enthalten, auch wenn diese Dinge selbst leer sind. Stellen Sie sich das wie eine Kiste leerer Kisten vor.
Der folgende Code zeigt eine Möglichkeit, die Funktion foo()
zu ändern, um das zu tun, was Sie wollen (und es zu testen). Ihre Vorstellung davon, was eine leere Liste ist, war überraschend schwierig zu entwickeln, teilweise, weil sie dem widerspricht, was die Sprache selbst für leer hält.Wie Sie sehen können, wurde die gesamte Logik, die sich mit der Bestimmung beschäftigt, ob die Liste gemäß Ihrer Definition "leer" ist, in eine separate Funktion mit der Bezeichnung empty_list()
verschoben, da dies wahrscheinlich wenig mit dem Rest von foo()
zu tun hat. Es ist nicht übermäßig komplex und wenn nichts anderes sollte Ihnen einen guten Ausgangspunkt bieten.
Sie haben auch nicht gesagt, was es tun soll, wenn das übergebene Argument keine Liste irgendeiner Art ist oder eine Liste war, aber nicht nur andere Listen oder Strings enthielt, so wie geschrieben, wird es ein erhöhen TypeError
Ausnahme - etwas, das ähnlich wie die meisten integrierten Python-Funktionen reagieren, wenn dies bei ihnen auftritt. Im Folgenden wird die Probe Code und sein Testausgang:
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'
Hier ist die Ausgabe, die es mit Python erzeugt 2.7: wirklich
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
Note- Ich verstehe bei x = [ ‚‘] die Liste ist nicht leer, aber trotzdem weißt du, dass es leer ist :) (oder es hat keine Werte/Daten, die benutzt werden können) –
Was versuchst du wirklich? Warum willst du ** '['', '']' als "leer" betrachtet werden? –
['', ''] ist kein großes Problem .... für diesen Satz (['', '']) kann verwendet werden !! –