在python中返回给定值的唯一索引

时间:2018-02-18 11:05:16

标签: python indices enumerate

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

如果我申请:

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无济于事,因为我有数千个输入的嵌套列表,任何建议我如何以理想的方式提取它?感谢。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

您还可以使用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]