【发布时间】: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