Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用内置对分查找列表中项目的索引_Python_Python 2.7_Python 3.x_Bisection - Fatal编程技术网

Python 如何使用内置对分查找列表中项目的索引

Python 如何使用内置对分查找列表中项目的索引,python,python-2.7,python-3.x,bisection,Python,Python 2.7,Python 3.x,Bisection,我想用以下参数创建一个函数: D = [(20832049, "hello", 3), (2042449014, "bye", 2), (208414004814, "cya", 3) 其中key表示每个元组的索引[1]处的元素,D是我给出的字典示例,hash只是对key进行散列 我的目标是创建一个函数,如果列表中有一个元组具有相同的键或散列(key),则该函数将查找元组的值 例如,如果我这样做了 (key, D, hash) 函数将返回值“3” 列表已排序您可以使用此功能: get("he

我想用以下参数创建一个函数:

D = [(20832049, "hello", 3), (2042449014, "bye", 2), (208414004814, "cya", 3)
其中key表示每个元组的索引[1]处的元素,D是我给出的字典示例,hash只是对key进行散列

我的目标是创建一个函数,如果列表中有一个元组具有相同的键或散列(key),则该函数将查找元组的值

例如,如果我这样做了

(key, D, hash)
函数将返回值“3”


列表已排序

您可以使用此功能:

get("hello", D, hash)

你想写这个函数,那么问题出在哪里呢?你的问题是什么?另外:标题应该是问题主体内容的摘要。与对分搜索相比,这不是很有效
def get(key, D, hash):
    for tuple in D:
        tuplelist = tuple.strip("()").split(", ")
        return (tuplelist[2] if tuplelist[1] == key)