I would like to extract an index of a list containing two or more specific elements.
Specifically
li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]
Indexing lists containing 2 and 3 from
list=[0,1,4,5,6]
I would like to create a list that will be .
Thank you for your cooperation.
You can use the following code.
li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]
newList = [ ]
for index, innerList in enumerate(li):
if2 in innerList and 3 in innerList:
newList.append(index)
print(newList)
# Output [0, 1, 4, 5, 6]
First, create an empty list newList=[]
with the new index.
In enumerate(li), extract the list (innerList) and index number in the list and turn the for statement.
Check if2innerList
to see if2innerList in the list and 3innerList
to see if3innerList in the list.
If both are included, add the index number to the newList.
Using numpy to set the variable li
to the numpy.ndarray
type makes it a little easier.
>>import numpy as np
>>li=np.array([
[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6],
[2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]
])
>>np.intersect 1d (*[np.where(li==k)[0]forkin(2,3)])
array([0,1,4,5,6])
This method uses the Boolean operation of NumPy.You can look for any number of values.
import numpy as np
def search_index(li, values):
arr=np.asarray(li)
arr_v=np.asarray(values).reshape(-1,1,1)
return(arr==arr_v).any(2).all(0).nonzero()[0]
Examples of operation:
In[11]: li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]
In[12]—search_index(li, [2,3])
Out [12]—array([0,1,4,5,6], dtype=int64)
In[13]—search_index(li, [2,3,4])
Out [13]—array([1,4,6], dtype=int64)
In[14]: search_index(li, [1])
Out [14]—array ([0,5], dtype=int64)
© 2024 OneMinuteCode. All rights reserved.