【发布时间】:2021-07-04 14:41:47
【问题描述】:
出于锻炼的原因,我实现了以下函数inverted_idx(data),它创建了一个倒排索引(从元组列表开始),其中的键字典的 是列表中的不同元素,与每个键关联的 值 是具有该键的所有元组的索引列表。
功能码为:
def inverted_idx(data):
rows = []
dictionary = {}
for idx, x in enumerate(data):
rows.append((idx, x))
for idx, x in rows:
for key in x:
if key in dictionary:
dictionary[key].append(idx)
else:
dictionary[key] = [idx]
return dictionary
通过在元组列表上使用它:
A = [(10, 4, 53), (0, 3, 10), (12, 6, 2), (8, 4, 0)(12, 3, 9)]
inverted_idx (data = A)
结果:
{10: [0, 1],
4: [0, 3],
53: [0],
0: [1, 3],
3: [1, 4],
12: [2, 4],
6: [2],
2: [2],
8: [3],
9: [4]}
该功能正常工作,现在我要做的是修改该功能
只为元组的那些元素创建倒排索引的顺序
占据特定位置。假设我想创建一个
倒排索引仅用于位置 1 的元素。
期望的输出是:
{4: [0, 3]
3: [1, 4]
6: [2]}
如何更改代码以便仅为给定位置的元素创建倒排索引?
我尝试过这样做:
def inverted_idx(data):
rows = []
dictionary = {}
for idx, x in enumerate(data):
rows.append((idx, x))
for idx, x[1] in rows: # trying to access the element in position 1
for key in x:
if key in dictionary:
dictionary[key].append(idx)
else:
dictionary[key] = [idx]
return dictionary
当然,我得到了以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-79-10c9adaea533> in <module>
1 A = [(10, 4, 53), (0, 3, 10), (12, 6, 2), (8, 4, 0), (12, 3, 9)]
2
----> 3 inverted_idx(data = A)
<ipython-input-78-d3f320303057> in inverted_idx(data)
4 for idx, x in enumerate(data):
5 rows.append((idx, x))
----> 6 for idx, x[1] in rows:
7 for key in x:
8 if key in dictionary:
TypeError: 'tuple' object does not support item assignment
【问题讨论】:
标签: python dictionary inverted-index