Python list search by key

Python : How to Check if an item exists in list ? | Search by Value or Condition

In this article we will discuss different ways to check if a given element exists in list or not.

Table of Contents

Introduction

Suppose we have a list of strings i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from']

Now let’s check if given list contains a string element ‘at’ ,

Check if element exists in list using python “in” Operator

Condition to check if element is in List :

It will return True, if element exists in list else return false.

Frequently Asked:

For example check if ‘at’ exists in list i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # check if element exist in list using 'in' if 'at' in listOfStrings : print("Yes, 'at' found in List : " , listOfStrings)

Condition to check if element is not in List :

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # check if element NOT exist in list using 'in' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings)

Check if element exist in list using list.count() function

count(element) function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # check if element exist in list using count() function if listOfStrings.count('at') > 0 : print("Yes, 'at' found in List : " , listOfStrings)

Check if element exist in list based on custom logic

Python any() function checks if any Element of given Iterable is True.

Let’s use it to check if any string element in list is of length 5 i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # Check if element exist in list based on custom logic # Check if any string with length 5 exist in List result = any(len(elem) == 5 for elem in listOfStrings) if result: print("Yes, string element with size 5 found")

Instead of condition we can use separate function in any to match the condition i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] def checkIfMatch(elem): if len(elem) == 5: return True; else : return False; # Check if any string that satisfies the condition # in checkIfMatch() function exist in List result = any(checkIfMatch for elem in listOfStrings)

Complete example is as follows,

def checkIfMatch(elem): if len(elem) == 5: return True; else : return False; # List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # Print the List print(listOfStrings) ''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print("Yes, 'at' found in List : " , listOfStrings) ''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings) ''' check if element exist in list using count() function ''' if listOfStrings.count('at') > 0 : print("Yes, 'at' found in List : " , listOfStrings) ''' check if element exist in list based on custom logic Check if any string with length 5 exist in List ''' result = any(len(elem) == 5 for elem in listOfStrings) if result: print("Yes, string element with size 5 found") ''' Check if any string that satisfies the condition in checkIfMatch() function exist in List ''' result = any(checkIfMatch for elem in listOfStrings) if result: print("Yes, string element with size 5 found")
['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'time' NOT found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, string element with size 5 found Yes, string element with size 5 found

Источник

Читайте также:  Writing log files in php

Поиск в списке словарей в Python

Поиск в списке словарей в Python

  1. Используйте функцию next() для поиска в списке словарей в Python
  2. Поиск в списке словарей с помощью функции filter() в Python
  3. Использование понимания списка для поиска в списке словарей в Python

В этом руководстве представлены методы, которые вы можете использовать для поиска в списке словарей в Python.

Используйте функцию next() для поиска в списке словарей в Python

Функцию next() можно использовать для предоставления результата в качестве следующего элемента в данном итераторе. Этот метод также требует использования цикла for для проверки процесса на соответствие всем условиям.

Следующий код использует функцию next() для поиска в списке словарей в Python.

lstdict = [  < "name": "Klaus", "age": 32 >,  < "name": "Elijah", "age": 33 >,  < "name": "Kol", "age": 28 >,  < "name": "Stefan", "age": 8 >  ] print(next(x for x in lstdict if x["name"] == "Klaus")) print(next(x for x in lstdict if x["name"] == "David")) 
 Traceback (most recent call last):  File "", line 8, in StopIteration 

Этот метод успешно реализуется, когда мы ищем имя, которое уже существует в списке словарей. Тем не менее, он выдает ошибку StopIteration при поиске имени, которого нет в списке словарей.

Однако эту проблему легко решить с помощью приведенного выше кода. Вы просто настраиваете и предоставляете значение по умолчанию с использованием немного другого API.

lstdict = [  < "name": "Klaus", "age": 32 >,  < "name": "Elijah", "age": 33 >,  < "name": "Kol", "age": 28 >,  < "name": "Stefan", "age": 8 >  ] print(next((x for x in lstdict if x["name"] == "David"), None)) 

Вместо того, чтобы искать сам элемент, мы также можем найти индекс элемента в Списке словарей. Для реализации этого мы можем использовать функцию enumerate() .

Следующий код использует функцию next() и функцию enumerate() для поиска и нахождения индекса элемента.

lstdict = [  < "name": "Klaus", "age": 32 >,  < "name": "Elijah", "age": 33 >,  < "name": "Kol", "age": 28 >,  < "name": "Stefan", "age": 8 >  ] print(next((i for i, x in enumerate(lstdict) if x["name"] == "Kol"), None)) 

Поиск в списке словарей с помощью функции filter() в Python

Функция filter(function, sequence) используется для сравнения sequence с function в Python. Он проверяет, является ли каждый элемент в последовательности истинным или нет, в соответствии с функцией. Мы можем легко найти элемент в списке словарей, используя функцию filter() с функцией lambda . В Python3 функция filter() возвращает объект класса filter . Мы можем преобразовать этот объект в список с помощью функции list() .

В следующем примере кода показано, как мы можем искать в списке словарей определенный элемент с помощью функций filter() и lambda .

listOfDicts = [  < "name": "Tommy", "age": 20 >,  < "name": "Markus", "age": 25 >,  < "name": "Pamela", "age": 27 >,  < "name": "Richard", "age": 22 > ] list(filter(lambda item: item['name'] == 'Richard', listOfDicts)) 

Мы провели поиск в списке словарей элемента, в котором ключ name равен Richard , используя функцию filter() с функцией lambda . Сначала мы инициализировали наш список словарей, listOfDicts , и использовали функцию filter() для поиска значений, которые соответствуют функции lambda lambda item: item[‘name’] == ‘Richard’ в Это. Наконец, мы использовали функцию list() для преобразования результатов в список.

Использование понимания списка для поиска в списке словарей в Python

Понимание списков — это относительно более короткий и очень изящный способ создания списков, которые должны формироваться на основе заданных значений уже существующего списка.

Мы можем использовать понимание списка, чтобы вернуть список, который производит результаты поиска списка словарей в Python.

Следующий код использует понимание списка для поиска по списку словарей в Python.

lstdict = [  < "name": "Klaus", "age": 32 >,  < "name": "Elijah", "age": 33 >,  < "name": "Kol", "age": 28 >,  < "name": "Stefan", "age": 8 >  ]  print([x for x in lstdict if x['name'] == 'Klaus'][0]) 

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Сопутствующая статья — Python Dictionary

Сопутствующая статья — Python List

Copyright © 2023. All right reserved

Источник

Using key in list to check if key is contained in list¶

Using key in list to iterate through a list can potentially take n iterations to complete, where n is the number of items in the list. If possible, you should change the list to a set or dictionary instead, because Python can search for items in a set or dictionary by attempting to directly accessing them without iterations, which is much more efficient.

Anti-pattern¶

The code below defines a list l and then calls if 3 in l to check if the number 3 exists in the list. This is inefficient. Behind the scenes, Python iterates through the list until it finds the number or reaches the end of the list.

l = [1, 2, 3, 4] # iterates over three elements in the list if 3 in l: print("The number 3 is in the list.") else: print("The number 3 is NOT in the list.") 

Best practice¶

Use a set or dictionary instead of a list¶

In the modified code below, the list has been changed to a set. This is much more efficient behind the scenes, as Python can attempt to directly access the target number in the set, rather than iterate through every item in the list and compare every item to the target number.

s = set([1, 2, 3, 4]) if 3 in s: print("The number 3 is in the list.") else: print("The number 3 is NOT in the list.") 

Источник

Оцените статью