【问题标题】:Dict Comprehension Index Error字典理解索引错误
【发布时间】:2018-04-03 09:44:35
【问题描述】:

我目前正在从 itertools groupby 对象构造一个字典推导,以构造一些字符串的查找字典。

#groupby iterable arranged by first 3 chars of each element of 'Titles' list.
lookup= groupby(sorted(Titles), key=itemgetter(0,1,2))
#key=concatenate the elements of the tuple, val=list of grouper iterable
lookdict={''.join(i):list(j) for i,j in lookup}

第二行给了我IndexError: string index out of range。我不知道这是否是 j、石斑可迭代或 dict comp 中的 join 调用的问题。 以下:

for i,j in lookup:
    print(''.join(i),j)

正如预期的那样,没有问题。

有必要将值作为列表,将键作为字符串,以避免每次查找时发生某种转换。

谁能指出我哪里出错了?

【问题讨论】:

  • 复制粘贴错误,已更正。
  • 我运行了你的代码并使用Titles = ['123abc', '123456', 'abcdef', 'abc123'] 得到lookdict == {'123': ['123456', '123abc'], 'abc': ['abc123', 'abcdef']}。你能发布一些示例数据吗?
  • 似乎您在 Titles 列表中有一个少于 3 个字符的元素。

标签: python dictionary itertools dictionary-comprehension


【解决方案1】:

当您向itemgetter 传递一个小于长度三的标题时,会发生这种情况:

itemgetter(0, 1, 2)('h')
IndexError: string index out of range

IndexError 在您理解之前不会发生,因为 lookup 包含 itertools._grouper 对象。这些对象是尚未解包的生成器。因此,通过在这些对象上调用 list,您正在尝试解压缩它们 - 导致错误。

我认为您应该将 key 更改为自定义函数,例如:

def key(item):
    return item[:3]

key('h')  # --> 'h'
key('hello')  # --> 'hel'

【讨论】:

  • 感谢您的建议
【解决方案2】:

这是一个非常有趣的问题。

您收到错误是因为 Titles 包含至少 1 个短于 3 个字符的元素。

在这种情况下,每次使用 lookup 的尝试都会失败。 for i, j in lookupfor i in loopup 甚至是简单的list(lookup)

Titles = ['abc', 'asf', 'asf', 'qwer', 'asfgsadfa', 'a']
lookup = groupby(sorted(Titles), key=itemgetter(0, 1, 2))
list(lookup)

Traceback (most recent call last):
 File "main.py", line 5, in <module>
 print(list(lookup))
IndexError: string index out of range

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2015-03-22
    • 2022-08-17
    相关资源
    最近更新 更多