【问题标题】:how can i get index of two of more duplicate characters in a string?如何获取字符串中两个或多个重复字符的索引?
【发布时间】:2017-11-25 13:35:21
【问题描述】:

我想在一个列表中存储两个或多个重复字符的实际索引。为此,我使用了 index() 但它返回所有重复字符的相同索引。 此问题的任何其他解决方案。

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:

让我们的列表和我们想要的元素定义如下:

my_list = [1, 3, 2, 4, 3, 3, 5, 3]
desired_element = 3

然后你就可以使用一个不错的 Python 内置函数了,enumerate():

indexes = [index for index, element in enumerate(my_list) if element == desired_element]
print(indexes)

正如预期的那样,输出是[1, 4, 5, 7]。


或者,以更好的格式:

def indexes(my_list, desired_element):
    return [index for index, element in enumerate(my_list) if element == desired_element]

然后使用indexes(list, element) 调用它。


如果你正在寻找效率(我怀疑你是):

def indexes2(my_list, desired_element):
    for index, element in enumerate(my_list):
        if element == desired_element:
            yield index

对于大型列表(据我测试),这要快 4-5 倍。请注意,这会返回一个生成器,为了可视化结果,您必须使用 list(...) 将其转换为列表。

【讨论】:

    【解决方案2】:

    使用 pandas,我们可以将其读入 pd 系列并一次性完成一些操作。

    import pandas as pd
    
    l = ['a','b','c','a','b']
    
    d = (pd.Series(l)[pd.Series(l).duplicated(keep=False)]
         .reset_index()
         .groupby(0)['index']
         .apply(list)
         .to_dict())
    
    d
    

    返回:

    {'a': [0, 3], 'b': [1, 4]}
    

    或者这个:

    d = (pd.Series(l)
         .reset_index()
         .groupby(0)['index']
         .apply(lambda x: list(x) if len(list(x)) > 1 else None)
         .dropna()
         .to_dict())
    

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多