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

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

What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.

Is there a way to specify what comparison operator to use?

Benyamin Jafari's user avatar

asked Mar 3, 2009 at 1:45

Himadri Choudhury's user avatar

2

From Dive Into Python:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

stivlo's user avatar

stivlo

83.2k31 gold badges142 silver badges199 bronze badges

answered Mar 3, 2009 at 1:52

Matt Howell's user avatar

3

If you just want to find out if an element is contained in the list or not:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

answered Feb 17, 2011 at 10:00

Eduardo's user avatar

EduardoEduardo

1,7811 gold badge11 silver badges5 bronze badges

0

The best way is probably to use the list method .index.

For the objects in the list, you can do something like:

def __eq__(self, other):
    return self.Value == other.Value

with any special processing you need.

You can also use a for/in statement with enumerate(arr)

Example of finding the index of an item that has value > 100.

for index, item in enumerate(arr):
    if item > 100:
        return index, item

Source

tedder42's user avatar

tedder42

23.2k12 gold badges86 silver badges100 bronze badges

answered Mar 3, 2009 at 1:51

Brian R. Bondy's user avatar

Brian R. BondyBrian R. Bondy

338k124 gold badges592 silver badges635 bronze badges

Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):

el = [x for x in mylist if x.attr == "foo"][0]

Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.

answered Sep 24, 2010 at 9:35

ThomasH's user avatar

ThomasHThomasH

22.1k13 gold badges60 silver badges61 bronze badges

3

assuming you want to find a value in a numpy array,
I guess something like this might work:

Numpy.where(arr=="value")[0]

Jorgesys's user avatar

Jorgesys

124k23 gold badges329 silver badges265 bronze badges

answered Jan 27, 2011 at 15:03

Sebastian Gurovich's user avatar

2

There is the index method, i = array.index(value), but I don’t think you can specify a custom comparison operator. It wouldn’t be hard to write your own function to do so, though:

def custom_index(array, compare_function):
    for i, v in enumerate(array):
        if compare_function(v):
            return i

answered Mar 3, 2009 at 1:50

David Z's user avatar

David ZDavid Z

127k27 gold badges253 silver badges278 bronze badges

I use function for returning index for the matching element (Python 2.6):

def index(l, f):
     return next((i for i in xrange(len(l)) if f(l[i])), None)

Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.

element = mylist[index(mylist, lambda item: item["name"] == "my name")]

If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:

def find_name(l, name):
     return l[index(l, lambda item: item["name"] == name)]

And then it is quite easy and readable:

element = find_name(mylist,"my name")

answered Oct 20, 2011 at 12:30

jki's user avatar

jkijki

4,6171 gold badge34 silver badges29 bronze badges

0

The index method of a list will do this for you. If you want to guarantee order, sort the list first using sorted(). Sorted accepts a cmp or key parameter to dictate how the sorting will happen:

a = [5, 4, 3]
print sorted(a).index(5)

Or:

a = ['one', 'aardvark', 'a']
print sorted(a, key=len).index('a')

answered Mar 3, 2009 at 1:52

Jarret Hardie's user avatar

Jarret HardieJarret Hardie

94.4k10 gold badges132 silver badges126 bronze badges

how’s this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

answered Mar 3, 2009 at 2:06

SingleNegationElimination's user avatar

2

I found this by adapting some tutos. Thanks to google, and to all of you ;)

def findall(L, test):
    i=0
    indices = []
    while(True):
        try:
            # next value in list passing the test
            nextvalue = filter(test, L[i:])[0]

            # add index of this value in the index list,
            # by searching the value in L[i:] 
            indices.append(L.index(nextvalue, i))

            # iterate i, that is the next index from where to search
            i=indices[-1]+1
        #when there is no further "good value", filter returns [],
        # hence there is an out of range exeption
        except IndexError:
            return indices

A very simple use:

a = [0,0,2,1]
ind = findall(a, lambda x:x>0))

[2, 3]

P.S. scuse my english

answered Oct 16, 2011 at 11:41

Gael's user avatar

1 / 1 / 1

Регистрация: 19.07.2016

Сообщений: 118

1

Получение элемента списка по имени

20.08.2016, 19:29. Показов 9069. Ответов 6


Студворк — интернет-сервис помощи студентам

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



0



4611 / 3148 / 1112

Регистрация: 21.03.2016

Сообщений: 7,842

20.08.2016, 19:35

2

вопрос простой. а откуда у элементов списка возьмутся имена?



0



Эксперт по компьютерным сетям

5889 / 3347 / 1033

Регистрация: 03.11.2009

Сообщений: 9,974

20.08.2016, 19:42

3



0



1 / 1 / 1

Регистрация: 19.07.2016

Сообщений: 118

21.08.2016, 07:50

 [ТС]

4

И имею ввиду чтобы к примеру есть список [‘Element1′,’element2′,’element3’] и нужно если я введу element2 получить 2 елемент в списке(тобиш 1 тк 0 1 2)



0



438 / 430 / 159

Регистрация: 21.05.2016

Сообщений: 1,338

21.08.2016, 08:07

5

Цитата
Сообщение от Сергей Мишин
Посмотреть сообщение

И имею ввиду чтобы к примеру есть список [‘Element1′,’element2′,’element3’] и нужно если я введу element2 получить 2 елемент в списке(тобиш 1 тк 0 1 2)

Хотите получить ‘element2’, введя ‘element2’ в запрос?

Если нужен индекс, то вот
yourlist.index(‘element2’)



0



Semen-Semenich

4611 / 3148 / 1112

Регистрация: 21.03.2016

Сообщений: 7,842

21.08.2016, 11:48

6

ну если вас словари не устраивают то можно устроить танец с бубном

Python
1
2
3
list_elem = ['Element1','element2','element3']
list_name = ['первый','второй','третий']
print(list_elem[list_name.index(input())])



0



I.G.O.R

3 / 3 / 1

Регистрация: 24.03.2011

Сообщений: 65

21.08.2016, 23:49

7

Python
1
2
3
4
5
6
7
list_elem = ['Element1','Element2','Element3']
find_elem = 'Element2'
for q in list_elem:
    if find_elem == q:
        print(list_elem.index(q))
        b = list_elem.index(q)
print(b)



0



Всем привет! Есть список товаров. Мне нужно найти условно «евроконтейнер пластиковый» в этом списке. Но записан он по разному:
-контейнер пластик;
-пластик евроконтейнер;
-евроконтейнер пластик 1100л. и т.д

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

names = s20['Товар'].unique()
names = str(names)
names = names.lower()

baskets = []
for i in names:
    if 'пластик' in i:
        baskets.append(i)
baskets


  • Вопрос задан

    более двух лет назад

  • 231 просмотр

str() выдаёт вам строку, так что это надо бы удалить, а так просто использовать генератор списка.
baskets = [x for x in names if 'пластик' in x]

Если нужно лишь найти все элементы со словом «пластик», то в принципе подойдёт.
baskets = [x for x in names if x.count('пластик')]
Но учитывая некоторую ошибку в самом начале, из-за которой список переделывается в str для применения lower(), немного изменяем это всё, чтоб алгоритм работал.

names = [x.lower() for x in names]

baskets = [x for x in names if x.count('пластик')]

Пригласить эксперта


  • Показать ещё
    Загружается…

28 мая 2023, в 19:46

500 руб./за проект

28 мая 2023, в 18:23

10000 руб./за проект

28 мая 2023, в 18:23

2500 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Как найди остатки незавершенного производства
  • Как исправить опечатку в одноклассниках
  • Как найти площадь стены в квадратных метрах
  • Как найти открытки с днем матери
  • Целая часть чисел как найти