d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Python- Object Index In Array
Add Reply New Topic New Poll
Member
Posts: 1,703
Joined: Jul 13 2009
Gold: 2,600.00
Jan 30 2016 02:30am
Hello,

Iam quite new in programming, so my question is simple.

Let a = ['abc 123', 'def 54344', 'gah dd'] be an array.

I want to get position of attribute containing string 'def', so the expected result would be like 1... for 'dd' like 2.

a.index function works only for whole string, not a part...

Any help is welcomed.
Member
Posts: 62,215
Joined: Jun 3 2007
Gold: 9,039.20
Jan 30 2016 04:06am
Code
>>> a = ['abc 123', 'def 54344', 'gah dd']
>>> a
['abc 123', 'def 54344', 'gah dd']
>>>
>>> for each in a:
... 'dd' in each
...
False
False
True


Code
>>> a = ['abc 123', 'def 54344', 'gah dd']
>>> for each in a:
... if 'dd' in each:
... print(a.index(each))
...
2


Code
>>> def indextual(search, array):
... for each in array:
... if search in each:
... return array.index(each)
...
>>> indextual('dd', a)
2


This post was edited by j0ltk0la on Jan 30 2016 04:11am
Member
Posts: 1,703
Joined: Jul 13 2009
Gold: 2,600.00
Jan 30 2016 03:24pm
Thank you :)
Member
Posts: 10,014
Joined: Jan 2 2007
Gold: 8,300.00
Feb 2 2016 08:31pm
To be honest, the answer above is a little ineffecient. Using a regex and searching within the string values is much faster. Plus, using enumerate instead of searching again through the list to find which one you are on is a much better choice.

Code
import re

a = ['abc 123', 'def 54344', 'gah dd']


def first_idx(term, iterable):
reg = re.compile('{}'.format(term))
for idx, val in enumerate(iterable):
if reg.search(val):
return idx

print(first_idx("dd", a))


But even that is a bit messy. Formating a string to build the reg seems a little hacky and could cause some problems. A better solution would be to take in a regex and then just use that.

Code
import re

a = ['abc 123', 'def 54344', 'gah dd']


def first_idx(reg, iterable):
for idx, val in enumerate(iterable):
if reg.search(val):
return idx

regex = re.compile('dd')
print(first_idx(regex, a))


If you aren't familiar with regex's and how they work I would highly recommend learning them. They are extremely useful, especially for any sort of string manipulation.

This post was edited by xARxJabala on Feb 2 2016 08:38pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll