在列表的同一子列表中搜索多个元素 [英] Search for Multiple Elements in Same Sublist of List

查看:182
本文介绍了在列表的同一子列表中搜索多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让Python在列表中搜索一个包含两个搜索词的子列表,但我却得到了一个包含一个或多个搜索的子列表.这是我的代码:

I am trying to get Python to search my list for a sublist which contains both of my search terms, but instead I get any sublist which contains one or more of the searches. Here is my code:

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

您的问题是,在您的代码中,您正在搜索第一个值,然后分别搜索第二个值.您需要进行搜索以确保两者都在同一个子列表中,否则,您将获得具有这些值之一的所有子列表.

Your problem was that in your code, you are searching for the first value, then searching for the second value, separately. You need to search to make sure both are in the same sublist, otherwise you'll get all sublists with either of those values.

break语句确保子列表仅打印一次.

The break statement makes sure the sublist is only printed once.

更新:

要回答您的评论,是的,它实际上比上面的代码轻得多.在这里:

To answer your comment, yes there is and it is actually much lighter than the code above. Here it is:

data = [[4,3],[4,7], [6,3], [9,2]]
search = [4,3]

if search in data:
    print 'yes',search

首先,您只需要将一个搜索变量search设置为要查找的搜索值的列表即可.

First, you only need one search variable, search, set to a list of the search values you are looking for.

第二,我们不再需要for循环,因为我们不再在子列表中寻找单个数字,我们只是在寻找item in list.

Second, we no longer need a for loop because we are no longer looking for individual numbers in a sublist, we are simply looking for item in list.

这的另一个好处是,现在您可以通过列表切片,添加新的搜索值或删除一些搜索值,以及维护所需的顺序来更新搜索变量.在此之前,您将必须添加新的搜索变量并将其添加到if语句中.

The other benefit of this, is that now you can update your search variable by list slicing, adding new search values, or removing some, and also maintaining the order you're looking for. Before, you would have to add new search variables AND add those to the if statement.

这篇关于在列表的同一子列表中搜索多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆