ABC
ABC

Reputation: 358

Python - Find the indices of elements of a list that match elements of another list

I have a longer list containing strings representing unique dates.

dates = ['20171021', '20171031', '20171102', '20171225', '20180101', '20180106',
 '20180126', '20180131', '20180312', '20180315', '20180330', '20180409',
 '20180414', '20180419', '20180421', '20180424', '20180426', '20180429',
 '20180501', '20180516', '20180524', '20180603', '20180605', '20180608', '20180613']

and a shorter list of strings with part of the dates (only those I am interested in)

selected_dates = ['20171021',  '20180106', '20180414', '20180426']

I want to use the second list to find the indices of the elements in the larger list that match the dates in this second list so the result would be

[0, 5, 12, 16]

Edit:

What I found by now is that I can use

dates.index('20171021')

to find a single index, but I cannot use

dates.index(selected_dates)

because this will search if list 2 is an element of list 1.

Upvotes: 1

Views: 69

Answers (2)

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3401

You can do it using index method.

>>> for date in selected_dates:
    print(dates.index(date))
0
5
12
16

Upvotes: 1

Celius Stingher
Celius Stingher

Reputation: 18377

You can use .index() in a list comprehension:

dates = ['20171021', '20171031', '20171102', '20171225', '20180101', '20180106',
 '20180126', '20180131', '20180312', '20180315', '20180330', '20180409',
 '20180414', '20180419', '20180421', '20180424', '20180426', '20180429',
 '20180501', '20180516', '20180524', '20180603', '20180605', '20180608', '20180613']

selected_dates = ['20171021',  '20180106', '20180414', '20180426']

filtered_dates = [dates.index(i) for i in selected_dates] #Find the index value of i in dates for each value in selected_dates

Output:

[0, 5, 12, 16]

Upvotes: 2

Related Questions