Как найти в списке нужную строку

Моя sql функция возвращает мне список кортежей. Пример: result = [('p',), ('a',)]. Мне нужно в одну строчку проверить содержится ли в данном списке данных строчка, условно говоря, ‘p’. Если использовать ‘p’ in result, выдает False т.к. он видит только два кортежа внутри. Как красиво и лаконично решить проблему?

Эникейщик's user avatar

Эникейщик

25.1k7 золотых знаков30 серебряных знаков46 бронзовых знаков

задан 19 авг 2022 в 13:07

Nomer's user avatar

1

я вот такое нагородил:

bool(sum([int("p" in el) for el in result]))

int("p" in el) – ставит 1, если “p” есть в кортеже, 0, если нет.

sum – считает итоговую сумму.

bool – выдает True, если сумма не 0 (т.е. хотя бы один кортеж содержал “p”).

Можно убрать bool(), тогда выдаст количество кортежей, которые содержат искомое.

ответ дан 19 авг 2022 в 13:16

Эникейщик's user avatar

ЭникейщикЭникейщик

25.1k7 золотых знаков30 серебряных знаков46 бронзовых знаков

2

можно фильтрануть:

bool(*filter(lambda x: x[0]=='p',result))

ответ дан 19 авг 2022 в 18:21

SergFSM's user avatar

SergFSMSergFSM

5,6501 золотой знак6 серебряных знаков17 бронзовых знаков

Given a list, the task is to write a Python program to check whether a list contains a particular string or not.

Examples:

Input: l=[1, 1.0, 'have', 'a', 'geeky', 'day']; s='geeky'
Output: geeky is present in the list
Input: l=['hello',' geek', 'have', 'a', 'geeky', 'day']; s='nice'
Output: nice is not present in the list

Method #1: Using in operator

The in operator comes handy for checking if a particular string/element exists in the list or not.

Example:

Python3

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky' 

if s in l:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

geeky is present in the list

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

Method #2: Using count() function

The count() function is used to count the occurrence of a particular string in the list. If the count of a string is more than 0, it means that a particular string exists in the list, else that string doesn’t exist in the list.

Example:

Python3

l = ['1', 1.0, 32, 'a', 'geeky', 'day']

s = 'prime'

if l.count(s) > 0:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

prime is not present in the list

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), no extra space is required

Method #3: Using List Comprehension

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. It is used to transform iterative statements into formulas.

Example:

Python3

l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']

s = 'geek'

compare = [i for i in l if s in l]

if len(compare) > 0:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

geeky is present in the list

Method #4: Using any() function

The any() function is used to check the existence of an element in the list. it’s like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list.

Example:

Python3

l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']

s = 'prime'

if any(s in i for i in l):

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

prime is not present in the list

The time and space complexity for all the methods are the same:

Time Complexity: O(n) -> as the built-in operators and functions like ‘in’, ‘count’ take O(n)

Space Complexity: O(n)

Method #5 : Using  list(),map(),join(),find() methods

Python3

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

nl=list(map(str,l))

x=" ".join(nl)

if x.find(s)!=-1:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time Complexity: O(n) -> built-in functions like join takes O(n)

Space Complexity: O(n)

Method #6 : Using Counter() function

Python3

from collections import Counter

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

freq = Counter(l)

if s in freq.keys():

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time Complexity: O(n) 

Auxiliary Space: O(n)

Method 7:  using operator.countOf() method

Python3

import operator as op

l = ['1', 1.0, 32, 'a', 'geeky', 'day']

s = 'prime'

if op.countOf(l, s):

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

prime is not present in the list

Time Complexity: O(N)

Auxiliary Space : O(1)

Method :  using try/except and index()

You can use the index() method to find the first index of a string in a list. If the string is present in the list, the index() method returns the first index of the string, otherwise it raises a ValueError. To check if a string is present in a list, you can wrap the index() method in a try-except block, and print a message indicating whether the string is present in the list or not.

Python3

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

try:

    index = l.index(s)

    print(f'{s} is present in the list at index {index}')

except ValueError:

    print(f'{s} is not present in the list')

Output

geeky is present in the list at index 4

Time Complexity: O(n) where n is the number of elements in the list, as the index() method iterates over the elements of the list until it finds the desired string or it exhausts the list.

Auxiliary Space: O(1), as the method uses only a few constant-sized variables, regardless of the size of the list.

Method : Using re

Algorithm

  1. Initialize a list l and a string s.
  2. Import the re module.
  3. Use the re.search() function to search for the string s in the list l.
  4. If a match is found, print that the string s is present in the list.
  5. If no match is found, print that the string s is not present in the list.

Python3

import re

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

for item in l:

    if isinstance(item, str) and re.search(s, item):

        print(f'{s} is present in the list')

        break

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time complexity: O(n*m), where n is the number of items in the list and m is the length of the longest string in the list.
Auxiliary Space: O(1), as we are not using any additional data structures in the program.

Method : Using operator.contains()

Approach

  1. Check whether given string is present in list using operator.contains()
  2. If yes display “string” is present in the  list
  3. If not display “string” is not present in the list

Python3

import operator

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

if operator.contains(l, s):

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time Complexity : O(N) N – length of list
Auxiliary Space : O(1)

Method : Using numpy:

  1. Import the numpy module.
  2. Initialize a list variable l with some string values.
  3. Initialize a string variable s with the value “prime”.
  4. Use a list comprehension to create a list of boolean values, where each value corresponds to whether the
  5. string s is present in the corresponding element of the list l.
  6. Use the np.any() method to check if any of the values in the resulting list is True.
  7. Print a message indicating whether the string s is present in the list or not, based on the value of res.

Python3

import numpy as np

l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']

s = 'prime'

res = np.any([s in i for i in l])

if res:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:
prime is not present in the list

Time complexity: O(nm), where n is the length of the input list and m is the length of the input string. The list comprehension has a time complexity of O(nm), as it iterates over each element of the list and checks if the string s is present in it.

Auxiliary Space: O(nm), where n is the length of the input list and m is the length of the input string. The list comprehension creates a new list of boolean values, which has a length of n, and each value in the list is a string of length m. Hence, the space complexity is O(nm).

Last Updated :
11 Apr, 2023

Like Article

Save Article

Если у вас есть список строк (List<String>) и вам требуется найти определённую строку в этом списке (или проверить, что список содержит нужную строку), вы можете это легко сделать несколькими способами:

  • С помощью стримов (этот способ подходит для Java 8 и выше)
  • С помощью итерирования по списку

Поиск строк с помощью стримов

Данный способ доступен для версии Java 8 и выше:

List<String> langs = new ArrayList<>();
langs.add("Java");
langs.add("JavaScript");
langs.add("Kotlin");
langs.add("Scala");
langs.add("Groovy");
langs.add("Python");

List<String> result = langs.stream()
        .filter(lang -> lang.contains("Java"))
        .collect(Collectors.toList());

System.out.println(result);

В консоль выведется:

[Java, JavaScript]

Чтобы учитывать полные совпадения строки, можно заменить эту строчку в коде:

.filter(lang -> lang.contains("Java"))

на следующую:

.filter(lang -> lang.equals("Java"))

В этом случае вывод в консоль будет следующим:

[Java]

Если же нужно просто проверить, есть ли искомая строка в списке, можно упростить код:

boolean result = langs.stream().anyMatch(lang -> lang.equals("Java"));

В данном случае в консоль напечатается значение true.

Поиск строк итерированием по списку

Найти строку можно и простым обходом всех элемента списка, допустим, с помощью цикла for-each:

List<String> langs = new ArrayList<>();
langs.add("Java");
langs.add("JavaScript");
langs.add("Kotlin");
langs.add("Scala");
langs.add("Groovy");
langs.add("Python");

for (String lang : langs) {
    if (lang.startsWith("Java")) {
        System.out.println(lang);
    }
}

Здесь мы обходим все строки, находящиеся в списке, и выводим те, которые начинаются на «Java». Результатом будет вывод на консоль:

Java
JavaScript

Заключение

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

  • startsWith – проверяет, начинается ли строка с указанной последовательности символов
  • equals / equalsIgnoreCase – сравнивает строки целиком (учитывая или игнорируя регистр букв)
  • contains – проверяет, содержит ли строка указанную последовательность символов

Автор оригинала: Pankaj Kumar.

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

Найти строку в списке в Python

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

Используя оператор ‘in’

Мы можем использовать Python’s в Оператор, чтобы найти строку в списке в Python. Это занимает два операнда А и B и имеет форму:

Здесь Ret_Value это логический, который оценивает Правда Если А лежит внутри B и Ложь иначе.

Мы можем напрямую использовать этот оператор следующим образом:

a = [1, 2, 3]

b = 4

if b in a:
    print('4 is present!')
else:
    print('4 is not present')

Выход

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

def check_if_exists(x, ls):
    if x in ls:
        print(str(x) + ' is inside the list')
    else:
        print(str(x) + ' is not present in the list')


ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython']

check_if_exists(2, ls)
check_if_exists('Hello', ls)
check_if_exists('Hi', ls)

Выход

2 is inside the list
Hello is inside the list
Hi is not present in the list

Это наиболее часто используемый и рекомендуемый способ поиска строки в списке. Но, для иллюстрации, мы покажем вам другие методы.

Использование списка понимание

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

Рассмотрим список ниже:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

Если вы хотите искать подстроку Привет Во всех элементах списка мы можем использовать список списков в следующем формате:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = [match for match in ls if "Hello" in match]

print(matches)

Это эквивалентно следующему коду, который просто имеет два цикла и проверки для условия.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = []

for match in ls:
    if "Hello" in match:
        matches.append(match)

print(matches)

В обоих случаях выход будет:

['Hello from AskPython', 'Hello', 'Hello boy!']

Как вы можете наблюдать, на выходе все совпадения содержат строку Привет как часть строки. Просто, не так ли?

Использование метода «любой ()»

Если вы хотите проверить наличие входной строки в любой Пункт списка, мы можем использовать любой () метод Чтобы проверить, надеется ли это.

Например, если вы хотите проверить, есть ли « Аскупптон ‘ является частью любого из элементов списка, мы можем сделать следующее:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

if any("AskPython" in word for word in ls):
    print(''AskPython' is there inside the list!')
else:
    print(''AskPython' is not there inside the list')

Выход

'AskPython' is there inside the list!

Использование фильтра и лямбдаса

Мы также можем использовать Фильтр () Метод на лямбда Функция , что является простой функцией, которая определяется только на этой конкретной линии. Подумайте о лямбде как мини-функция, которые не могут быть использованы после звонка.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

# The second parameter is the input iterable
# The filter() applies the lambda to the iterable
# and only returns all matches where the lambda evaluates
# to true
filter_object = filter(lambda a: 'AskPython' in a, ls)

# Convert the filter object to list
print(list(filter_object))

Выход

У нас есть то, что мы ожидали! Только одна строка соответствует нашей функции фильтра, и это действительно то, что мы получаем!

Заключение

В этой статье мы узнали о том, как мы можем найти строку с помощью списка ввода с разными подходами. Надеюсь, это помогло вам с вашей проблемой!

использованная литература

  • Журналдав Статья На поиск строки в списке
  • Stackoverflow вопрос При нахождении строки внутри списка

На чтение 4 мин Просмотров 5к. Опубликовано 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. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Добавить комментарий