如何在另一个列表中搜索字符串? - python

How to search for a string inside another list? - python

我需要在列表中搜索姓名。

当我这样做时我没有问题:

#contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix Tadeo','Police','Argentina']]
    contacts = ['Juan Corrales','FELIX']
    name = 'Juan Corrales'
    
    if name in contacts:
        print("name found")
    else:
        print("name not found")

但是当我在双重列表中查找它时,它没有找到它。

我该如何解决这个问题?

contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix Tadeo','Police','Argentina']]
#contacts = ['Juan Corrales','Felix Tadeo']
name = 'Juan Corrales'

if name in contacts:
    print("name found")
else:
    print("name not found")

那是因为 contacts 包含列表作为元素,而不是字符串。您可以做的是展平 contacts 列表,然后在那里搜索:

contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix Tadeo','Police','Argentina']]
#contacts = ['Juan Corrales','Felix Tadeo']
flat_contacts = [item for sublist in contacts for item in sublist]
name = 'Juan Corrales'

if name in flat_contacts:
    print("name found")
else:
    print("name not found")

您需要将列表展平为一维。您可以通过多种方式进行:

# For when there are only 2 sublists
if name in contacts[0]+contacts[1]:
# When there are n sublists
if name in [i for t in contacts for i in t]:

in 运算符只看表面,不会扫描所有嵌套子列表。考虑这个例子:

>>> a = [1, 2, 3, 4]
>>> b = [[1, 2], [3, 4]]

>>> 1 in a
True
>>> 1 in b
False
>>> [1, 2] in b
True

import itertools
contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix Tadeo','Police','Argentina']]
name = 'Juan Corrales'

if {name}.issubset(itertools.chain.from_iterable(contacts)):
    print("Name Found")
else:
    print("Name not Found")

输出:

Name Found

您的 if 语句正在联系人列表中查找字符串,但您的联系人列表包含多个列表。一种方法是使用 itertools 加入内部列表并在此处查找您的值。这是一个示例代码:

import itertools

contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix Tadeo','Police','Argentina']]
#contacts = ['Juan Corrales','Felix Tadeo']
name = 'Juan Corrales'

if name in list(itertools.chain.from_iterable(contacts)):
    print("name found")
else:
    print("name not found")

请记住,只有当你有一个列表列表时,它才会对你有用。

您可以使用any函数:

contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix 
Tadeo','Police','Argentina']]
#contacts = ['Juan Corrales','Felix Tadeo']
name = 'Juan Corrales'

print("name found") if any(name in contact for contact in contacts) else print("name not found")

最简洁,不需要依赖

contacts = [['1','Juan Corrales','Loyer','Peru'],['2','Felix Tadeo','Police','Argentina']]
name = 'Juan Corrales'
found = any([True for c in contacts if name in c]) #True

只需遍历联系人列表中的列表,然后检查它们的内部 - 如果在其中任何一个中找到,瞧!!!我们知道了。