我试图让 Python 在我的列表中搜索包含我的两个搜索词的子列表,但我得到的是包含一个或多个搜索的任何子列表。这是我的代码:
search1 = 4
search2 = 3
data = [[4,3],[4,7], [6,3], [9,2]]
found = False
for sublist in data:
if search1 in sublist:
print("there", sublist)
if search2 in sublist:
print("there", sublist)
found = True
if(found==False):
print("not there")
print(data)
if(found==False):
print("not there")
print(data)
我得到的输出是:
there [4,3] #I only want this sublist, and only once.
there [4,3]
there [6,3] #I don't want this sublist.
干杯! 5813
请您参考如下方法:
for sublist in data:
if search1 in sublist and search2 in sublist:
print("there", sublist)
break
您的问题是,在您的代码中,您正在搜索第一个值,然后分别搜索第二个值。您需要搜索以确保两者都在同一个子列表中,否则您将获得具有这些值之一的所有子列表。
break 语句确保子列表只打印一次。
Update:
要回答您的评论,是的,它实际上比上面的代码轻得多。在这里:
data = [[4,3],[4,7], [6,3], [9,2]]
search = [4,3]
if search in data:
print 'yes',search
首先,您只需要一个搜索变量 search,将其设置为您要查找的搜索值列表。
其次,我们不再需要 for 循环,因为我们不再在子列表中查找单个数字,我们只是在列表中查找 item。
这样做的另一个好处是,现在您可以通过列表切片、添加新的搜索值或删除一些值来更新您的搜索变量,同时保持您要查找的顺序。以前,您必须添加新的搜索变量并将它们添加到 if 语句中。
