我有三个排序数组:
>>> a = arange(10)
>>> b = arange(3,12)
>>> c = arange(-2,8)
>>> print(a)
[0 1 2 3 4 5 6 7 8 9]
>>> print(b)
[ 3 4 5 6 7 8 9 10 11]
>>> print(c)
[-2 -1 0 1 2 3 4 5 6 7]
我想获取包含在所有其他数组中的每个数组元素的索引列表。
在此示例中,每个数组中的索引对应于数字 3 - 7
所以像这样:
a_inds, b_inds, c_inds = get_unq_inds(a,b,c)
a_inds = [3,4,5,6,7] (or [False, False, False, True, True, True, True, True, False, False])
b_inds = [0,1,2,3,4] (or [True, True, True, True, True, False, False, False, False])
等
基本上,我想扩展此处提供的解决方案:(在两个数组中查找常用值的索引)到 3 个数组。(或者,如果你觉得雄心勃勃,"n"数组)
你可以这样做:
def get_unq_inds(a, b, c):
uniq_vals = list(set(a).intersection(b).intersection(c))
return [a.index(x) for x in uniq_vals], [b.index(x) for x in uniq_vals], [c.index(x) for x in uniq_vals]
# you can use this for boolean values
#return [x in uniq_vals for x in a], [x in uniq_vals for x in b], [x in uniq_vals for x in c]
输出
a_inds, b_inds, c_inds = get_unq_inds(range(9), range(3,12), range(-2,8))
>>> a_inds, b_inds, c_inds
([3, 4, 5, 6, 7], [0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
布尔值的输出:
[False, False, False, True, True, True, True, True, False]
[True, True, True, True, True, False, False, False, False]
[False, False, False, False, False, True, True, True, True, True]
现场演示在这里
您可以组合所有范围以在set
中获取公共元素,然后针对此进行测试:
>>> ranges = [range(9), range(3,12), range(-2,8)]
>>> s = set.intersection(*map(set,ranges))
>>> [[i for i,x in enumerate(sublist) if x in s] for sublist in ranges]
[[3, 4, 5, 6, 7], [0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
这将适用于任意数量的输入列表。
或者类似地使用与 Ranjan 想法相同的@Ashish s
(请注意,索引可能不是有序的,因为我们正在迭代无序set()
,尽管在实践中它们可能会由于 Python 哈希整数的方式而保持顺序):
[[sublist.index(x) for x in s] for sublist in ranges]
对于布尔值列表,可以使用列表推导式。
a_inds = [x in b and x in c for x in a]