【问题标题】:Returning unique indices for given value in python在python中返回给定值的唯一索引
【发布时间】:2018-07-28 18:56:42
【问题描述】:

我有一个列表,我需要根据给定的唯一值提取所有元素的索引号。

如果我申请:

test3 = ["P3","P35","P35","P3","P2"]
actual_state = "P3"
indexes = [n for n, x in enumerate(test3) if actual_state in x]

返回:

[0, 1, 2, ,3]

但输出应该是:

[0, 3]

P3 也存在于 P35 中,重命名 P35 将无济于事,因为我有数千个输入的嵌套列表,有什么建议可以如何以所需的方式提取它?谢谢。

【问题讨论】:

    标签: python indices enumerate


    【解决方案1】:

    in 更改为==,因为in 也测试子字符串:

    indexes = [n for n, x in enumerate(test3) if actual_state == x]
    print (indexes)
    [0, 3]
    

    【讨论】:

      【解决方案2】:

      您也可以使用collections.defaultdict() 对唯一字符串的索引进行分组,然后只需访问actual_state 的键:

      from collections import defaultdict
      
      test3 = ["P3","P35","P35","P3","P2"]
      actual_state = "P3"
      
      d = defaultdict(list)
      for i, test in enumerate(test3):
          d[test].append(i)
      
      print(d[actual_state])
      # [0, 3]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-18
        • 1970-01-01
        • 2021-11-24
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        相关资源
        最近更新 更多