[英]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.因为这将搜索列表 2 是否是列表 1 的元素。
You can use .index()
in a list comprehension:您可以在列表理解中使用.index()
:
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]
You can do it using index
method.您可以使用index
方法来完成。
>>> for date in selected_dates:
print(dates.index(date))
0
5
12
16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.