【发布时间】:2017-05-22 11:19:45
【问题描述】:
我的目标是让我的 bisect 函数工作,因为它没有。我想检查项目是否在 D 中,但不知道该怎么做,需要帮助..
def get(key, D, hasher=hash):
try:
item = hasher(int(key))
except ValueError:
item = hasher(str(key))
for item1 in range(len(D)):
print(D[item1])
print()
for value in range(len(D)):
print(value)
print()
print(D[value])
position = bisect.bisect_left(D[value], item)
print(position)
D=[(0, 'richard', 69), (0, 'richard', 113), (1, 'placed', 91), (9, 'richardo', 30)]
如果 bisect 函数为真,我希望这个函数返回位置(索引)。
但是,我不确定如何检查“项目”是否在我的列表“D”中。我以为我可以for循环抛出范围(len(D)),然后使用索引检查项目是否在每个元组中,但它会产生错误。
我的输出:
[(0, 'richard', 69), (0, 'richard', 113), (1, 'placed', 91), (9, 'richardo', 30)]
(0, 'richard', 69)
(0, 'richard', 113)
(1, 'placed', 91)
(9, 'richardo', 30)
0
(0, 'richard', 69)
Traceback (most recent call last):
File "binarysearch.py", line 129, in <module>
get("richardo", D, poorhash)
File "binarysearch.py", line 60, in get
position = bisect.bisect_left(D[value], item)
TypeError: unorderable types: str() < int()
【问题讨论】:
-
它的 bisect.bisect_left(D[value], item) 坏了。
-
好的,我不知道 bisect 模块,仍然混淆了你实际调用 get() 的内容以及为什么
-
D在使用 bisect 之前需要进行排序。如果您在搜索item之前排序D,您将丢失*原始位置信息- 可以吗?D中元组的哪个项/索引item对应?
标签: python python-2.7 python-3.x syntax-error tuples