python - 访问列出的元组中的元素,在我的函数中创建错误

标签 python python-2.7 python-3.x syntax-error tuples

我的目标是使我的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函数为true,我希望此函数返回位置(索引)。

但是,我不确定如何检查“D”列表中是否包含“item”。我以为可以循环抛出range(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()

最佳答案

当元素的函数为True时如何获取列表元素索引的问题是生成器或理解的基本习语,甚至具有更整洁的枚举形式。

当然,它们也可以编写为for循环,并且for循环可以从枚举器对象运行,或者如果参数像列表一样可迭代,则可以依赖于迭代

D=[(0, 'richard', 69), (0, 'richard', 113), (1, 'placed', 91), (9, 'richardo', 30)]


item = 91 # or try 'richard'

indxs = [n for n, elem in enumerate(D) if (item in elem)]
print(indxs)

for i in indxs:
    print('index:', i, '  element:', D[i])

[2]
index: 2   element: (1, 'placed', 91)

bool(boolean) 比较(item in elem)在不假定类型匹配的前提下是“类型不可知的”,只返回False,不会引发错误

我不明白您对bisect lib函数的意图,因为它们不返回 bool(boolean) 值,并且仅操作可订购的对象,而不是混合的int和字符串

您也不需要显式地使用哈希函数,因为这是元组之间在内部进行的==
# if you want the next higher level, then compare tuples for equality

item = (9, 'richardo', 30)

indxs = [n
         for n, elem in enumerate(D)
         if (item == elem) ]

print('compare element:', indxs)

compare element: [3]

关于python - 访问列出的元组中的元素,在我的函数中创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526976/

相关文章:

python - 如何在不知道索引的情况下从 numpy 数组中删除对象

python - 使用 python 纯 SASL,我们现在可以编写 python 客户端来访问 Message Hub 吗?

Python tox 和 py.test : how to run just a single test rather than the whole test suite

python - 验证 Tkinter.Text 小部件?

python - 从默认模型 gpt-2-simple python 上的输入生成文本

python - 使用子进程在 python 2.7 中获取尾命令输出

python - 在 python 中检查区分大小写的 os.path.isfile(filename)

python - 检查FTP连接是否成功打开,文件是否已上传到Python中的FTP

python - 处理Python HTTP连接超时

python - 作为另一个函数的参数的函数