【问题标题】:Accessing elements in listed tuples, creating errors in my function访问列出的元组中的元素,在我的函数中创建错误
【发布时间】: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


【解决方案1】:

当元素的函数是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)

布尔比较 (item in elem) 在不预设类型匹配的意义上是“类型不可知的”,只是返回 False,不会引发错误

我不明白您对 bisect lib 函数的意图,因为它们不返回布尔值,并且只操作可排序对象,而不是混合整数和字符串

您也不需要显式地使用哈希函数,因为这就是 == 元组之间在内部所做的事情

# 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多