Как найти элемент в списке по условию

Let’s assume I’m creating a simple class to work similar to a C-style struct, to just hold data elements. I’m trying to figure out how to search a list of objects for objects with an attribute equaling a certain value. Below is a trivial example to illustrate what I’m trying to do.

For instance:

class Data:
    pass

myList = []

for i in range(20):
    data = Data()
    data.n = i
    data.n_squared = i * i
    myList.append(data)

How would I go about searching the myList list to determine if it contains an element with n == 5?

I’ve been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I’m not sure. I might add that I’m having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren’t available to me.

DevPlayer's user avatar

DevPlayer

5,3431 gold badge25 silver badges20 bronze badges

asked Feb 28, 2009 at 18:06

m0j0's user avatar

1

You can get a list of all matching elements with a list comprehension:

[x for x in myList if x.n == 30]  # list of all elements with .n==30

If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do

def contains(list, filter):
    for x in list:
        if filter(x):
            return True
    return False

if contains(myList, lambda x: x.n == 3)  # True if any element has .n==3
    # do stuff

Ali Afshar's user avatar

Ali Afshar

40.8k12 gold badges94 silver badges109 bronze badges

answered Feb 28, 2009 at 18:11

Adam Rosenfield's user avatar

Adam RosenfieldAdam Rosenfield

388k96 gold badges512 silver badges586 bronze badges

3

Simple, Elegant, and Powerful:

A generator expression in conjuction with a builtin… (python 2.5+)

any(x for x in mylist if x.n == 10)

Uses the Python any() builtin, which is defined as follows:

any(iterable) ->
Return True if any element of the iterable is true. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

h3xStream's user avatar

h3xStream

6,2032 gold badges46 silver badges57 bronze badges

answered Feb 28, 2009 at 20:15

gahooa's user avatar

gahooagahooa

130k12 gold badges97 silver badges100 bronze badges

3

Just for completeness, let’s not forget the Simplest Thing That Could Possibly Work:

for i in list:
  if i.n == 5:
     # do something with it
     print "YAY! Found one!"

answered Feb 28, 2009 at 18:20

Charlie Martin's user avatar

Charlie MartinCharlie Martin

110k24 gold badges193 silver badges260 bronze badges

0

[x for x in myList if x.n == 30]               # list of all matches
[x.n_squared for x in myList if x.n == 30]     # property of matches
any(x.n == 30 for x in myList)                 # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30]  # indices of all matches

def first(iterable, default=None):
  for item in iterable:
    return item
  return default

first(x for x in myList if x.n == 30)          # the first match, if any

answered Feb 28, 2009 at 18:19

Markus Jarderot's user avatar

Markus JarderotMarkus Jarderot

86.4k21 gold badges136 silver badges138 bronze badges

2

filter(lambda x: x.n == 5, myList)

answered Feb 28, 2009 at 18:22

vartec's user avatar

vartecvartec

130k36 gold badges217 silver badges244 bronze badges

3

You can use in to look for an item in a collection, and a list comprehension to extract the field you are interested in. This (works for lists, sets, tuples, and anything that defines __contains__ or __getitem__).

if 5 in [data.n for data in myList]:
    print "Found it"

See also:

  • Contains Method
  • In operation

Markus Jarderot's user avatar

answered Feb 28, 2009 at 18:23

Tom Dunham's user avatar

Tom DunhamTom Dunham

5,7592 gold badges30 silver badges27 bronze badges

Another way you could do it is using the next() function.

matched_obj = next(x for x in list if x.n == 10)

m0j0's user avatar

m0j0

3,4545 gold badges27 silver badges33 bronze badges

answered Jun 16, 2020 at 6:01

SEMICS's user avatar

SEMICSSEMICS

1713 silver badges4 bronze badges

You should add a __eq__ and a __hash__ method to your Data class, it could check if the __dict__ attributes are equal (same properties) and then if their values are equal, too.

If you did that, you can use

test = Data()
test.n = 5

found = test in myList

The in keyword checks if test is in myList.

If you only want to a a n property in Data you could use:

class Data(object):
    __slots__ = ['n']
    def __init__(self, n):
        self.n = n
    def __eq__(self, other):
        if not isinstance(other, Data):
            return False
        if self.n != other.n:
            return False
        return True
    def __hash__(self):
        return self.n

    myList = [ Data(1), Data(2), Data(3) ]
    Data(2) in myList  #==> True
    Data(5) in myList  #==> False

answered Feb 28, 2009 at 18:10

Johannes Weiss's user avatar

Johannes WeissJohannes Weiss

52.2k16 gold badges102 silver badges136 bronze badges

Consider using a dictionary:

myDict = {}

for i in range(20):
    myDict[i] = i * i

print(5 in myDict)

answered Mar 1, 2009 at 1:14

dan-gph's user avatar

dan-gphdan-gph

16.2k12 gold badges61 silver badges79 bronze badges

2

Use the following list comprehension in combination with the index method:

data_n = 30
j = [data.n for data in mylist].index(data_n)
print(mylist[j].data.n == data_n)

Tomerikoo's user avatar

Tomerikoo

18.1k16 gold badges45 silver badges60 bronze badges

answered Apr 18, 2021 at 18:55

Matt Koch's user avatar

На чтение 4 мин Просмотров 5.3к. Опубликовано 03.03.2023

Содержание

  1. Введение
  2. Поиск методом count
  3. Поиск при помощи цикла for
  4. Поиск с использованием оператора in
  5. В одну строку
  6. Поиск с помощью лямбда функции
  7. Поиск с помощью функции any()
  8. Заключение

Введение

В ходе статьи рассмотрим 5 способов поиска элемента в списке Python.

Поиск методом count

Метод count() возвращает вхождение указанного элемента в последовательность. Создадим список разных цветов, чтобы в нём производить поиск:

colors = ['black', 'yellow', 'grey', 'brown']

Зададим условие, что если в списке colors присутствует элемент ‘yellow’, то в консоль будет выведено сообщение, что элемент присутствует. Если же условие не сработало, то сработает else, и будет выведена надпись, что элемента отсутствует в списке:

colors = ['black', 'yellow', 'grey', 'brown']

if colors.count('yellow'):
    print('Элемент присутствует в списке!')
else:
    print('Элемент отсутствует в списке!')

# Вывод: Элемент присутствует в списке!

Поиск при помощи цикла for

Создадим цикл, в котором будем перебирать элементы из списка colors. Внутри цикла зададим условие, что если во время итерации color приняла значение ‘yellow’, то элемент присутствует:

colors = ['black', 'yellow', 'grey', 'brown']

for color in colors:
    if color == 'yellow':
         print('Элемент присутствует в списке!')

# Вывод: Элемент присутствует в списке!

Поиск с использованием оператора in

Оператор in предназначен для проверки наличия элемента в последовательности, и возвращает либо True, либо False.

Зададим условие, в котором если ‘yellow’ присутствует в списке, то выводится соответствующее сообщение:

colors = ['black', 'yellow', 'grey', 'brown']

if 'yellow' in colors:
    print('Элемент присутствует в списке!')
else:
    print('Элемент отсутствует в списке!')

# Вывод: Элемент присутствует в списке!

В одну строку

Также можно найти элемент в списке при помощи оператора in всего в одну строку:

colors = ['black', 'yellow', 'grey', 'brown']

print('Элемент присутствует в списке!') if 'yellow' in colors else print('Элемент отсутствует в списке!')

# Вывод: Элемент присутствует в списке!

Или можно ещё вот так:

colors = ['black', 'yellow', 'grey', 'brown']

if 'yellow' in colors: print('Элемент присутствует в списке!')

# Вывод: Элемент присутствует в списке!

Поиск с помощью лямбда функции

В переменную filtering будет сохранён итоговый результат. Обернём результат в список (list()), т.к. метода filter() возвращает объект filter. Отфильтруем все элементы списка, и оставим только искомый, если он конечно присутствует:

colors = ['black', 'yellow', 'grey', 'brown']

filtering = list(filter(lambda x: 'yellow' in x, colors))

Итак, если искомый элемент находился в списке, то он сохранился в переменную filtering. Создадим условие, что если переменная filtering не пустая, то выведем сообщение о присутствии элемента в списке. Иначе – отсутствии:

colors = ['black', 'yellow', 'grey', 'brown']

filtering = list(filter(lambda x: 'yellow' in x, colors))

if filtering:
    print('Элемент присутствует в списке!')
else:
    print('Элемент отсутствует в списке!')

# Вывод: Элемент присутствует в списке!

Поиск с помощью функции any()

Функция any принимает в качестве аргумента итерабельный объект, и возвращает True, если хотя бы один элемент равен True, иначе будет возвращено False.

Создадим условие, что если функция any() вернёт True, то элемент присутствует:

colors = ['black', 'yellow', 'grey', 'brown']

if any(color in 'yellow' for color in colors):
    print('Элемент присутствует в списке!')
else:
    print('Элемент отсутствует в списке!')

# Вывод: Элемент присутствует в списке!

Внутри функции any() при помощи цикла производится проверка присутствия элемента в списке.

Заключение

В ходе статьи мы с Вами разобрали целых 5 способов поиска элемента в списке Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Время чтения 3 мин.

Существует несколько способов проверки наличия элемента в списке в Python:

  1. Использование метода index() для поиска индекса элемента в списке.
  2. Использование оператора in для проверки наличия элемента в списке.
  3. Использование метода count() для подсчета количества вхождений элемента.
  4. Использование функции any().
  5. Функция filter() создает новый список элементов на основе условий.
  6. Применение цикла for.

Содержание

  1. Способ 1: Использование метода index()
  2. Способ 2: Использование «оператора in»
  3. Способ 3: Использование функции count()
  4. Синтаксис
  5. Пример
  6. Способ 4: использование понимания списка с any()
  7. Способ 5: Использование метода filter()
  8. Способ 6: Использование цикла for

Способ 1: Использование метода index()

Чтобы найти элемент в списке Python, вы можете использовать метод list index(). Список index() — это встроенный метод, который ищет элемент в списке и возвращает его индекс.

Если один и тот же элемент присутствует более одного раза, метод возвращает индекс первого вхождения элемента.

Индекс в Python начинается с 0, а не с 1. Таким образом, через индекс мы можем найти позицию элемента в списке.

streaming = [‘netflix’, ‘hulu’, ‘disney+’, ‘appletv+’]

index = streaming.index(‘disney+’)

print(‘The index of disney+ is:’, index)

Выход

The index of disney+ is: 2

Метод list.index() принимает единственный аргумент, элемент, и возвращает его позицию в списке.

Способ 2: Использование «оператора in»

Используйте оператор in, чтобы проверить, есть ли элемент в списке.

main_list = [11, 21, 19, 46]

if 19 in main_list:

  print(«Element is in the list»)

else:

  print(«Element is not in the list»)

Выход

Вы можете видеть, что элемент «19» находится в списке. Вот почему оператор in возвращает True.

Если вы проверите элемент «50», то оператор in вернет False и выполнит оператор else.

Способ 3: Использование функции count()

Метод list.count() возвращает количество вхождений данного элемента в списке.

Синтаксис

Метод count() принимает единственный элемент аргумента: элемент, который будет подсчитан.

Пример

main_list = [11, 21, 19, 46]

count = main_list.count(21)

if count > 0:

  print(«Element is in the list»)

else:

  print(«Element is not in the list»)

Выход

Мы подсчитываем элемент «21», используя список в этой функции example.count(), и если он больше 0, это означает, что элемент существует; в противном случае это не так.

Способ 4: использование понимания списка с any()

Any() — это встроенная функция Python, которая возвращает True, если какой-либо элемент в итерируемом объекте имеет значение True. В противном случае возвращается False.

main_list = [11, 21, 19, 46]

output = any(item in main_list for item in main_list if item == 22)

print(str(bool(output)))

Выход

Вы можете видеть, что в списке нет «22». Таким образом, нахождение «22» в списке вернет False функцией any(). Если функция any() возвращает True, элемент в списке существует.

Способ 5: Использование метода filter()

Метод filter() перебирает элементы списка, применяя функцию к каждому из них.

Функция filter() возвращает итератор, который перебирает элементы, когда функция возвращает значение True.

main_list = [11, 21, 19, 46]

filtered = filter(lambda element: element == 19, main_list)

print(list(filtered))

Выход

В этом примере мы используем функцию filter(), которая принимает функцию и перечисляет ее в качестве аргумента.

Мы использовали лямбда-функцию, чтобы проверить, совпадает ли входной элемент с любым элементом из списка, и если это так, он вернет итератор. Чтобы преобразовать итератор в список в Python, используйте функцию list().

Мы использовали функцию list() для преобразования итератора, возвращаемого функцией filter(), в список.

Способ 6: Использование цикла for

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

main_list = [11, 21, 19, 46]

for i in main_list:

  if(i == 46):

    print(«Element Exists»)

Выход

В этом примере мы прошли список элемент за элементом, используя цикл for, и если элемент списка совпадает с входным элементом, он напечатает «Element exists».

The list is an important container in python as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses the Fastest way to check if a value exists in a list or not using Python.

Example:

list = test_list = [1, 6, 3, 5, 3, 4]
Input: 3  # Check if 3 exist or not.
Output: True
Input: 7  # Check if 7 exist or not.
Output: False

Method 1: Naive Method

In the Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list. Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. The list need not be sorted to practice this approach of checking.

Example 1: Check if an element exists in the list using the if-else statement

Python3

lst=[ 1, 6, 3, 5, 3, 4 ]

i=7

if i in lst:

    print("exist")

else:

    print("not exist")

Time Complexity: O(1)
Auxiliary Space: O(n), where n is total number of elements.

Example 2: Check if an element exists in the list using a loop 

Python3

test_list = [1, 6, 3, 5, 3, 4]

for i in test_list:

    if(i == 4):

        print("Element Exists")

Output:

Element Exists

Time Complexity: O(n)
Auxiliary Space: O(1)

Example 3: Check if an element exists in the list using “in” 

Python3

test_list = [1, 6, 3, 5, 3, 4]

if (4 in test_list):

    print("Element Exists")

Output:

Element Exists

Example 4: Check if an element exists in the list using any() function

Python3

test_list = [1, 6, 3, 5, 3, 4]

result = any(item in test_list for item in test_list)

print("Does string contain any list element : " +str(bool(result)))

Output:

Does string contain any list element : True

Method 2: Check if an element exists in the list using count()

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List. Demonstrating to check the existence of elements in the list using count().

Python3

test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")

exist_count = test_list.count(15)

if exist_count > 0:

    print("Yes, 15 exists in list")

else:

    print("No, 15 does not exists in list")

Output:

Checking if 15 exists in list
Yes, 15 exists in list

Method 3: Check if an element exists in the list using sort + bisect_left + set

Converting the list into the set and then using it can possibly be more efficient than only using it. But having efficiency for a plus also has certain negatives. One among them is that the order of the list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list. In the conventional binary search way of testing element existence, hence list has to be sorted first and hence does not preserve the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL.

Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not.

Demonstrating to check existence of element in list using set() + in and sort() + bisect_left()

Python3

from bisect import bisect_left ,bisect

test_list_set = [ 1, 6, 3, 5, 3, 4 ]

test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]

print("Checking if 4 exists in list ( using set() + in) : ")

test_list_set = set(test_list_set)

if 4 in test_list_set :

    print ("Element Exists")

print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ")

test_list_bisect.sort()

if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4):

    print ("Element Exists")

else:

    print("Element doesnt exist")

Output:

Checking if 4 exists in list ( using set() + in) : 
Element Exists
Checking if 4 exists in list ( using sort() + bisect_left() ) : 
Element Exists

Method 4: Using find() method

Python3

test_list = [10, 15, 20, 7, 46, 2808]

print("Checking if 15 exists in list")

x=list(map(str,test_list))

y="-".join(x)

if y.find("15") !=-1:

    print("Yes, 15 exists in list")

else:

    print("No, 15 does not exists in list")

Output

Checking if 15 exists in list
Yes, 15 exists in list

Method 5: Using Counter() function

Below is the implementation:

Python3

from collections import Counter

test_list = [10, 15, 20, 7, 46, 2808]

frequency = Counter(test_list)

if(frequency[15] > 0):

    print("Yes, 15 exists in list")

else:

    print("No, 15 does not exists in list")

Output

Yes, 15 exists in list

Method 6: Using try-except block

One additional approach to check if an element exists in a list is to use the index() method. This method returns the index of the first occurrence of the element in the list, or throws a ValueError if the element is not present in the list. To use this method, you can wrap the call to index() in a try-except block to catch the ValueError and return False if it occurs:

Python3

def element_exists(lst, element):

  try:

    lst.index(element)

    return True

  except ValueError:

    return False

test_list = [1, 6, 3, 5, 3, 4]

print(element_exists(test_list, 3))

print(element_exists(test_list, 7))

Time complexity: O(n), where n is the length of the list. The index() method iterates through the list to find the element, so the time complexity is linear.

Auxiliary Space: O(1). This approach does not require any additional space.

Approach 7: Using Set
Time complexity: O(1) average case as checking for an element in a set takes constant time on average.
Space complexity: O(n) as it creates a new set from the list to store its elements.

Python3

def check_element_exists_set(lst, target):

  return target in set(lst)

test_list = [1, 6, 3, 5, 3, 4]

target = 3

print("Exists using set: ", check_element_exists_set(test_list, target))

Output

Exists using set:  True

Last Updated :
22 Feb, 2023

Like Article

Save Article

Пускай имеется такая задача: дан список с численными элементами. Требуется найти и вернуть первый отрицательный элемент. Казалось бы, должна быть какая-нибудь встроенная функция для этого, но нет. Придется писать ее самим. Решение в лоб:

items = [1, 3, 5, -17, 20, 3, -6]

for x in items:
    if x < 0:
        print(x)
        break
else:
    print('not found')

Такое решение работает, но выглядит скорее по-бейсиковски, нежели чем по-питоновски. Пытаясь проявить смекалку, некоторые извращаются и пишут так:

result = list(filter(lambda x: x < 0, items))[0]
print(result)

По-моему, стало гораздо сложнее, хоть и в одну строку. А может лучше так:

result = [x for x in items if x < 0][0]

Что ж, теперь лаконичнее, но все равно не идеал. Какая самая большая ошибка здесь? Что в первом, что во втором случае идет перебор всего итератора до конца, а потом отбрасываются все лишние значения, кроме нулевого индекса. Тогда как изначальный код останавливается, найдя нужно значение, экономя и время, и память.

Правильное решение

Лучше использовать встроенную функцию next – она возвращает следующий элемент из итератора, а в качестве итератора мы напишем генераторное выражение с if. Вот так:

result = next(x for x in items if x < 0)

Вот это коротко, экономно и очень по-питоновски (in a pythonic way). Остается одна проблемка: если элемент не найден, что будет брошено исключение StopIteration. Чтобы подавить его, достаточно вторым аргументом в next передать значение по-умолчанию. Если оно задано, то оно будет возвращено вместо возбуждения исключения, если в итераторе нет элементов, то есть не найдено удовлетворяющих условию элементов в исходной коллекции. И не забыть обернуть генераторное выражение в скобки:

items = [1, 2, 4]
result = next((x for x in items if x < 0), 'not found')
print(result)  # not found

С произвольной функцией, задающей критерий поиска (ее еще называют предикат – predicate) это выглядит так:

def is_odd(x):
    return x % 2 != 0

result = next(x for x in items if is_odd(x))
# или еще лучше
result = next(filter(is_odd, items))

Так как в Python 3 filter работает лениво, как и генератор, она не «обналичивает» весь исходный список через фильтр, а лишь идет до первого удачно-выполненного условия. Любите итераторы! ✌️ 

Специально для канала @pyway. Подписывайтесь на мой канал в Телеграм @pyway 👈 

3 366

Понравилась статья? Поделить с друзьями:
  • Волшебная водка сталкер чистое небо как найти
  • Как найти диаметр шины автомобиля
  • Как исправить кадастровую ошибку в росреестре через мфц
  • Как составить формулу в экселе для сводной таблицы
  • Как найти будущую невесту