在元组列表中使用bisect?

use*_*919 11 python python-3.3

我试图弄清楚如何在元组列表中使用bisect

[(3, 1), (2, 2), (5, 6)]
Run Code Online (Sandbox Code Playgroud)

如何根据每个元组中的[1]将该列表一分为二?

list_dict [(69, 8), (70, 8), ((65, 67), 6)]
tup1,tup2 (69, 8) (70, 8)
list_dict [((65, 67), 6)]
fst, snd ((65, 67),) (6,)
Run Code Online (Sandbox Code Playgroud)

我正在插入二等分

idx = bisect.bisect(fst, tup1[1]+tup2[1])
Run Code Online (Sandbox Code Playgroud)

哪能给我 unorderable types: int() < tuple()

Evg*_*eev 13

在某些情况下只是简单

bisect(list_of_tuples, (3, None))
Run Code Online (Sandbox Code Playgroud)

就足够了.

因为None将比任何整数都小,所以这将为您提供以至少3开头的第一个元组的索引,或者len(list_of_tuples)如果所有这些都小于3.请注意这list_of_tuples是排序的.

  • 这在Python 3中不起作用.如果你传递确切的数字3,你会得到`TypeError:unorderable types:int()<NoneType()`.但是`bisect(list_of_tuples,(3,))`会没事的. (9认同)

Yar*_*Yar 6

从版本开始,3.10您可以将键传递给bisect方法来指定您要搜索的索引 -更多信息请参见此处

key 指定一个参数的键函数,用于从数组中的每个元素中提取比较键。为了支持搜索复杂记录,key 函数不应用于 x 值。

import bisect
tuple_list = [(4, 117), (10, 129), (30, 197)]
# search among first indices - returns 1
bisect.bisect_left(tuple_list, 10, key=lambda i: i[0])
# search among second indices - returns 1
bisect.bisect_left(tuple_list, 129, key=lambda i: i[1])
# 2
bisect.bisect_left(tuple_list, 130, key=lambda i: i[1])
Run Code Online (Sandbox Code Playgroud)


Jon*_*nts 5

您可以将值分离到单独的列表中。

from bisect import bisect

data = [(3, 1), (2, 2), (5, 6)]
fst, snd = zip(*data)
idx = bisect(fst, 2)
Run Code Online (Sandbox Code Playgroud)

但是请注意,bisect要正常工作,您的数据确实应该排序...

  • 使用二等分的主要优点是线性时间搜索。以线性时间方式复制列表意味着您也可以进行线性搜索。 (2认同)