Python—查找与另一个列表元素匹配的列表元素的索引
我有一个较长的列表,其中包含表示唯一日期的字符串Python—查找与另一个列表元素匹配的列表元素的索引,python,Python,我有一个较长的列表,其中包含表示唯一日期的字符串 dates = ['20171021', '20171031', '20171102', '20171225', '20180101', '20180106', '20180126', '20180131', '20180312', '20180315', '20180330', '20180409', '20180414', '20180419', '20180421', '20180424', '20180426', '20180429'
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]
您可以在列表中使用.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]
您可以使用索引方法来完成
您可以使用索引方法来完成
你被困在哪里?你能把你试过的贴出来吗?您看过类似的问题吗:您可以使用嵌套for循环和简单比较来解决这个问题。试着分享你第一次做的事情。你被困在哪里了?你能把你试过的贴出来吗?您看过类似的问题吗:您可以使用嵌套for循环和简单比较来解决这个问题。试着分享你第一次做的事情。