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]
推荐阅读
- javascript - 如何使用简单的 ajax jQuery 对 DialogFlow V2 进行 http 调用?
- sql - PSQL - 双精度类型的无效输入语法:“null”;
- swift - 使用 ARSCNView 后从场景中删除节点
- ruby-on-rails - 某些特定 RSpec 测试的自定义 VCR 请求匹配选项
- django - 从 Django Rest Api 获取并显示数据
- arrays - Visual Basic 解析嵌套的 JSON 文件
- c# - 升级到 .Net Core 2.1 时找不到版本 (>= 2.1.0) 的软件包 Microsoft.Extensions.SecretManager.Tools
- arrays - 找到第一个缺失的正整数
- java - 如何使用 Github Java API 将外部协作者添加到组织中的存储库?
- docker - 启用 TLS 的反向代理 (Traefik) 背后的 Docker Registry - 远程错误:证书错误