Python - 查找与另一个列表的元素匹配的列表元素的索引

标签 python

我有一个更长的列表,其中包含表示唯一日期的字符串。

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']

我想使用第二个列表来查找较大列表中与第二个列表中的日期匹配的元素的索引,因此结果将是

[0, 5, 12, 16]

编辑:

我现在发现我可以使用

dates.index('20171021')

查找单个索引,但我无法使用

dates.index(selected_dates)

因为这将搜索列表 2 是否是列表 1 的元素。

最佳答案

您可以在列表理解中使用.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

输出:

[0, 5, 12, 16]

关于Python - 查找与另一个列表的元素匹配的列表元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59988699/

相关文章:

python - 想通过以文本格式保留所有行和列来使用 python 创建 excel 文件

python - Pandas 按顺序删除行

python - 启用 scrapy 记录器时如何查看打印语句的输出

python - 单元测试面向方面的功能

python - 模板语法错误 : 'settings_tags' is not a valid tag library

python - 艾托夫投影,Python

python - 多处理 Python 库中的慢速数据结构

python - 将悬停工具提示添加到 Bokeh 直方图

python - 如何显示数据框中的非数值

python - 绘图中的 3d 和 2d 子图