1

我正在寻找一种有效的方法来映射值列表,比如

x = [1,2,3,4,5,6,7,8,9] 

到另一个列表,包含相同总范围的值列表,例如

z = [[1,2,3], [4,5,6], [7,8,9]]. 

我需要知道的基本上是来自 x 的值对应于 z 的索引。x[0]=1将对应于z[0],因为它落在 z 的第一个 bin 中,其中x[7]=8将对应于z[2],因为它落在第三个 bin 中。

如何识别每个 x 值的 z 子列表的索引?在我的例子中,x 有大约 50,000 个值,z 有大约 5,000 个子列表,而且我有很多这样的列表,所以我正在寻找一种方法来尽可能快地做到这一点。

4

3 回答 3

5

您可以在此处使用字典:

>>> x = [1,2,3,4,5,6,7,8,9]
>>> z = [[1,2,3], [4,5,6], [7,8,9]]
>>> dic = {y :i for i,a in enumerate(z) for y in a}
>>> dic[7]
2
>>> dic[8]
2
>>> dic[1]
0
于 2013-05-21T08:03:31.127 回答
0

看来您正在按间隔搜索,您可以使用间隔树。一个快速的谷歌显示https://github.com/tylerkahn/intervaltree-python,经过一些修改,我希望它能够非常有效地工作。

我修改后的模块位于http://pastebin.com/M6rpYt44并简单地添加一个顺序属性key, 如果它不存在的话。

from IntervalTree import *

x = [1,2,3,4,5,6,7,8,9]
z = [[1,2,3], [4,5,6], [7,8,9]]

intervals = [Interval(l[0],l[-1]) for l in z]
it = IntervalTree(intervals)

# search
[it.search(i)[0].key for i in x]
# [0, 0, 0, 1, 1, 1, 2, 2, 2]
于 2013-05-21T09:24:33.100 回答
0
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [[1,2,3], [4,5,6], [7,8,9]]
>>> map(lambda x: [i for i in range(len(y)) if y[i].count(x) > 0], x)
[[0], [0], [0], [1], [1], [1], [2], [2], [2]]
>>> 
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [[1,2,3], [4,5,6], [7,8,9], [1,2,3]]
>>> map(lambda x: [i for i in range(len(y)) if y[i].count(x) > 0], x)
[[0, 3], [0, 3], [0, 3], [1], [1], [1], [2], [2], [2]]
>>> 
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 9, 7]]
>>> map(lambda x: [i for i in range(len(y)) if y[i].count(x) > 0], x)
[[0, 3], [0], [0], [1], [1], [1], [2, 3], [2], [2, 3]]
>>> 
>>> x = [ 4, 5, 6, 7, 8, 9, 1, 2, 3]
>>> y = [[1, 2, 3], [7, 8, 9], [1, 9, 7], [4, 5, 6]]
>>> map(lambda x: [i for i in range(len(y)) if y[i].count(x) > 0], x)
[[3], [3], [3], [1, 2], [1], [1, 2], [0, 2], [0], [0]]
>>> 

>>> x = [ 4, 5, 6, 7, 8, 9, 1, 2, 3]
>>> y = [[1, 2, 3], [7, 8, 9], [1, 9, 7], [4, 5, 6]]
>>> d = {}
>>> d.update(map(lambda x: (x, [i for i in range(len(y)) if y[i].count(x) > 0]), x))
>>> d
{1: [0, 2], 2: [0], 3: [0], 4: [3], 5: [3], 6: [3], 7: [1, 2], 8: [1], 9: [1, 2]}
>>> 

我认为它有效!

于 2013-05-21T09:04:24.330 回答