python - 字典理解索引错误

标签 python dictionary python-itertools dictionary-comprehension

我目前正在从 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:字符串索引超出范围。我无法判断这是否是 j、石斑鱼迭代或 dict comp 中的 join 调用的问题。 以下内容:

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

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

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

谁能指出我哪里出错了?

最佳答案

当您将长度小于三的标题传递给 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'

关于python - 字典理解索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49626962/

相关文章:

python - 根据行条件替换 nan 值

python - 如何使用 Pandas 对一系列值进行编码

dictionary - dict.keys 不打印列表但打印 ListView 的问题

arrays - 如何在 iOS Swift 中将值数组附加到 tableView 中?

python - 使用 python itertools 生成自定义迭代

python - MinMaxScaler 仅生成正值

python - 如何在 python 数据表中查找和标记重复项

swift - 比嵌套字典更合适的解决方案?

python - 使列表中所有可能的值组合具有不同的大小

python - itertools 产品使用太多内存