假设有两个 Python 列表:
my_list = ['a', 'bb', 'c', 'bb', 'cc', 'bbc']
sublist = ['bb', 'bb', 'bbc']
显然,子列表 由*my_list* 的第一个、第三个和第五个元素组成。现在我想得到
给定这两个列表,索引 [1, 3, 5]
。有什么简单的方法可以做到这一点吗?
注意:
- 列表可以有相同的元素。
- 子列表保持原始列表中元素的顺序。
最佳答案
您可以使用生成器:
def indices(lst, items):
last_index = 0
for item in items:
last_index += lst.index(item, last_index + 1) + 1
yield last_index
关于Python:查找与给定子列表匹配的列表索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15847809/