如何在以下列表中搜索包含字符串“abc”的项目?

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

以下检查“abc”是否在列表中,但未检测到“abc-123”和“abc-456”:

if 'abc' in xs:

当前回答

使用筛选器获取具有“abc”的所有元素:

>>> xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> list(filter(lambda x: 'abc' in x, xs))
['abc-123', 'abc-456']

还可以使用列表理解:

>>> [x for x in xs if 'abc' in x]

其他回答

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

for item in my_list:
    if (item.find('abc')) != -1:
        print ('Found at ', item)
any('abc' in item for item in mylist)
def find_dog(new_ls):
    splt = new_ls.split()
    if 'dog' in splt:
        print("True")
    else:
        print('False')


find_dog("Is there a dog here?")

我是Python新手。我得到了下面的代码,使其易于理解:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
    if 'abc' in item:
       print(item)

使用筛选器获取具有“abc”的所有元素:

>>> xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> list(filter(lambda x: 'abc' in x, xs))
['abc-123', 'abc-456']

还可以使用列表理解:

>>> [x for x in xs if 'abc' in x]