返回 python 中给定值的唯一索引
Returning unique indices for given value in python
我有一个列表,我需要根据给定的唯一值提取所有元素的索引号。
如果我申请:
test3 = ["P3","P35","P35","P3","P2"]
actual_state = "P3"
indexes = [n for n, x in enumerate(test3) if actual_state in x]
这个returns:
[0, 1, 2, ,3]
但输出应该是:
[0, 3]
P35 中也存在 P3,重命名 P35 无济于事,因为我有包含数千个输入的嵌套列表,请问如何以所需方式提取它?谢谢
将in
更改为==
,因为in
测试子串也:
indexes = [n for n, x in enumerate(test3) if actual_state == x]
print (indexes)
[0, 3]
您还可以使用 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]
我有一个列表,我需要根据给定的唯一值提取所有元素的索引号。
如果我申请:
test3 = ["P3","P35","P35","P3","P2"]
actual_state = "P3"
indexes = [n for n, x in enumerate(test3) if actual_state in x]
这个returns:
[0, 1, 2, ,3]
但输出应该是:
[0, 3]
P35 中也存在 P3,重命名 P35 无济于事,因为我有包含数千个输入的嵌套列表,请问如何以所需方式提取它?谢谢
将in
更改为==
,因为in
测试子串也:
indexes = [n for n, x in enumerate(test3) if actual_state == x]
print (indexes)
[0, 3]
您还可以使用 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]