如果元素位于列表中,则在Python中无法正常工作
我有两个清单,如:如果元素位于列表中,则在Python中无法正常工作,python,list,Python,List,我有两个清单,如: readFile = [['String1'], [], ['String2'], []] stringList = ['String1','String2'] 但是,在使用Python的if语句之后: for value in stringList: if not value in readStocksFile: print(value+" does not exist in this list") 根据Python,值String1不在
readFile = [['String1'], [], ['String2'], []]
stringList = ['String1','String2']
但是,在使用Python的if语句之后:
for value in stringList:
if not value in readStocksFile:
print(value+" does not exist in this list")
根据Python,值String1不在我的readFile列表中,这是不正确的。我做错了什么?因为列表在列表中吗
readFile = [['String1'], [], ['String2'], []]
试试这个
readFile = ['String1','' , 'String2', '']
如果您想将检查保持为“此字符串是否在字符串列表中”,那么我将使用any方法:
readFile = [['String1'], [], ['String2'], []]
stringList = ['String1','String2']
for value in stringList:
if not any(value in sublist for sublist in readFile):
print(value + " does not exist in this list")
行
如果没有(文件中的值对应于readFile中的文件)
表示:如果值
不在子列表中,则执行打印。这是因为String1
是数据类型字符串,['String1']
是数据类型列表,因此String1
不会显示在readFile
中。要使String1
位于readFile
中,readFile
应为:
readFile=['String1','','String2','']
这不起作用,因为readFile中没有字符串值,而是有更多具有字符串值的列表,因此纠正它的一种方法是:
if not [value] in readFile
由于该值为“String1”,因此if语句在readFile中变为if非['String1']
而readFile包含以下元素:[“String1”]
,[]
,[“String2”]
因此,由于[“String1”]
在readFile列表中,因此不会触发if语句。“String1值不在我的readFile列表中,这不是真的”-它是真的readFile
有4个元素,其中没有一个是'String1'
。更具体地说,'String1'!=['String1']
。您需要检查列表列表中的每个子列表。