Python :检查列表列表中是否不存在字符串
Python : Checking if a string does not exist in a list of lists
我有一个简单的代码生成列表列表并用字符串 "null" 填充它,但是当我尝试检查 "null" 是否不存在于整个列表列表中时,它没有给我预期的结果
lst = [ ['null']*4 for n in xrange(2) ]
print lst
if ('null' not in lst):
print "testing"
此代码总是打印 "testing",我不知道为什么。
感谢您的解释
谢谢
展平列表,然后对展平的列表进行 "is not in" 检查:
flattened = [x for x in sublist for sublist in lst]
if "null" not in flattened:
print("testing")
您的列表 lst
不是字符串列表,而是字符串列表的列表。
您可以尝试:
if any('null' in lst2 for lst2 in lst):
作为你的测试:也就是说,return True
如果你的主列表的任何子列表中有一个字符串 'null'
,lst
.
我有一个简单的代码生成列表列表并用字符串 "null" 填充它,但是当我尝试检查 "null" 是否不存在于整个列表列表中时,它没有给我预期的结果
lst = [ ['null']*4 for n in xrange(2) ]
print lst
if ('null' not in lst):
print "testing"
此代码总是打印 "testing",我不知道为什么。 感谢您的解释 谢谢
展平列表,然后对展平的列表进行 "is not in" 检查:
flattened = [x for x in sublist for sublist in lst]
if "null" not in flattened:
print("testing")
您的列表 lst
不是字符串列表,而是字符串列表的列表。
您可以尝试:
if any('null' in lst2 for lst2 in lst):
作为你的测试:也就是说,return True
如果你的主列表的任何子列表中有一个字符串 'null'
,lst
.