我需要Python来搜索给定列表的所有子列表,但是当我搜索仅包含其中一个列表的元素时,这不起作用。例如,这是我的代码:
data = [[4,5],[4,7]]
search = 4
for sublist in data:
if search in sublist:
print("there", sublist)
else:
print("not there")
print(data)
如果我的搜索包含在列表的所有子列表中,则此方法非常有效。但是,如果我的搜索是例如5,那么我得到:
there [4,5] #I only want this part.
not there # I don't want the rest.
[[4, 5], [4, 7]]
编辑:
基本上,我需要Python列出搜索所包含的所有列表,但如果搜索只包含在一个子列表中,我只需要print("there", sublist)
。换句话说,我只希望Python识别搜索所在的位置,而不是输出不存在的位置,因此没有print("not there") print(data)
。
答案 0 :(得分:2)
尝试使用布尔标记。例如:
data = [[4,5],[4,7]]
search = 5
found = false
for sublist in data:
if search in sublist:
print("there", sublist)
found = true
if found == false:
print("not there")
print(data)
这样打印数据就在for循环之外,每次找到不包含搜索的子列表时都不会打印。
答案 1 :(得分:1)
data = [[4,5],[4,7]]
search = 4
found_flag = False
for sublist in data:
if search in sublist:
print("there", sublist)
found_flag = True
# else:
# print("not there")
# print(data)
if not found_flag:
print('not found')
如果您不想对不包含搜索值的子列表执行任何操作,则没有理由包含else
子句。
在else
块之后使用for
很有效(但这只会找到一个条目)(doc):
data = [[4,5],[4,7]]
search = 4
for sublist in data:
if search in sublist:
print("there", sublist)
break
else:
print 'not there'
如果它通过整个循环而没有点击else
,它将执行break
块。
答案 2 :(得分:1)
你可能想写的东西:
data = [[4,5],[4,7]]
search = 4
found = False
for sublist in data:
if search in sublist:
found = True
break
# do something based on found
更好的方式来写:
any(search in sublist for sublist in data)
答案 3 :(得分:0)
您可能正在寻找
for sublist in data:
if search in sublist:
print("there", sublist)
break
else:
print("not there")
print(data)
答案 4 :(得分:0)
数据= [[4,5],[4,7],[5,6],[4,5]]
search = 5
表示数据中的子列表:
if search in sublist:
print "there in ",sublist
else:
print "not there in " , sublist
[4,5]
不在[4,7]
那里[5,6]
[4,5]
我刚试过你的代码,我在搜索5时没有看到任何错误