First create a dictionary containing in the index location of each item in the list (you state that all items are unique, hence no issue with duplicate keys).
Then use the dictionary to look up each item's index location which is average time complexity O(1).
my_list = ['ab', 'sd', 'ef', 'de']
d = {item: idx for idx, item in enumerate(my_list)}
items_to_find = ['sd', 'ef', 'sd']
>>> [d.get(item) for item in items_to_find]
[1, 2, 1]
Answer from Alexander on Stack OverflowTaken from https://www.programiz.com/python-programming/online-compiler/?ref=409055e9 :
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Output: The index of i: 2
Say that the list was much bigger, and you don't know the contents, but you know 'i' is in it more than once. What would be the best way to find all instances of 'i'?
Thanks so much! <3
python - Find index for multiple elements in a long list - Stack Overflow
python - Access multiple elements of list knowing their index - Stack Overflow
python - finding index of multiple items in a list - Stack Overflow
python - How to find the indices of items in a list, which are present in another list? - Stack Overflow
First create a dictionary containing in the index location of each item in the list (you state that all items are unique, hence no issue with duplicate keys).
Then use the dictionary to look up each item's index location which is average time complexity O(1).
my_list = ['ab', 'sd', 'ef', 'de']
d = {item: idx for idx, item in enumerate(my_list)}
items_to_find = ['sd', 'ef', 'sd']
>>> [d.get(item) for item in items_to_find]
[1, 2, 1]
You could use a dictionary with elements from lst as the key and index and as the value. Search in a dictionary is O(1).
You can use operator.itemgetter:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
Or you can use numpy:
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]
But really, your current solution is fine. It's probably the neatest out of all of them.
Alternatives:
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
Sounds like a one-liner Python is able to do!
[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]
This will work, but assumes you do not care about case sensitivity:
myList = ["what is your name","Hi, how are you","What about you","How about a coffee","How are you"]
duplicate = "how are you"
index_list_of_duplicate = [i for i,j in enumerate(myList) if duplicate in j.lower()]
print index_list_of_duplicate
[1,4]
N = []
for i in range(len(L)):
if L[i] in R:
N.append(i)
or avoid indexing by using enumerate
N = []
for i, l in enumerate(L):
if l in R:
N.append(i)
or with a generator
N = [i for i in range(len(L)) if L[i] in R]
or with arrays
import numpy as np
N=np.where(np.isin(L,R))
[i for i,l in enumerate(L) if l in R]
It seems that you're trying to find occurrences of a word inside a string: the re library has a function called finditer that is ideal for this purpose. We can use this along with a list comprehension to make a list of the indexes of a word:
>>> import re
>>> word = "foo"
>>> string = "Bar foo lorem foo ipsum"
>>> [x.start() for x in re.finditer(word, string)]
[4, 14]
This function will find matches even if the word is inside another, like this:
>>> [x.start() for x in re.finditer("foo", "Lorem ipsum foobar")]
[12]
If you don't want this, encase your word inside a regular expression like this:
[x.start() for x in re.finditer("\s+" + word + "\s+", string)]
Probably not the fastest/best way but it will work. Used in rather than == in case there were quotations or other unexpected punctuation aswell! Hope this helps!!
def getWord(string, word):
index = 0
data = []
for i in string.split(' '):
if i.lower() in word.lower():
data.append(index)
index += 1
return data
You can use a list comprehension with enumerate:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
The iterator enumerate(my_list) yields pairs (index, item) for each item in the list. Using i, x as loop variable target unpacks these pairs into the index i and the list item x. We filter down to all x that match our criterion, and select the indices i of these elements.
While not a solution for lists directly, numpy really shines for this sort of thing:
import numpy as np
values = np.array([1,2,3,1,2,4,5,6,3,2,1])
searchval = 3
ii = np.where(values == searchval)[0]
returns:
ii ==>array([2, 8])
This can be significantly faster for lists (arrays) with a large number of elements vs some of the other solutions.