在Python中获取带索引列表的重复字符串,可以通过以下步骤实现:
以下是一个示例代码,展示如何在Python中获取带索引列表的重复字符串:
def find_duplicate_strings_with_indices(lst):
seen = set()
duplicates = {}
for index, item in enumerate(lst):
if item in seen:
if item in duplicates:
duplicates[item].append(index)
else:
duplicates[item] = [seen[item], index]
else:
seen[item] = index
return {key: value for key, value in duplicates.items() if len(value) > 1}
# 示例列表
lst = ["apple", "banana", "apple", "orange", "banana", "grape"]
# 获取带索引的重复字符串
result = find_duplicate_strings_with_indices(lst)
print(result)
enumerate
函数遍历列表,获取每个元素及其索引。seen
集合中,说明是重复元素,将其索引添加到duplicates
字典中。{'apple': [0, 2], 'banana': [1, 4]}
通过以上方法,你可以高效地获取带索引列表中的重复字符串,并记录其出现的索引位置。
领取专属 10元无门槛券
手把手带您无忧上云