[英]Reducing duplicates in Python list of lists
我正在编写一个程序,该程序读取多个文件,然后为其中的术语建立索引。 我能够将文件读入python中的2d数组(列表)中,但是随后我需要删除第一列中的重复项,并将索引存储在新列中,该列具有重复单词的首次出现。
例如:
['when', 1]
['yes', 1]
['', 1]
['greg', 1]
['17', 1]
['when',2]
第一列是术语,第二列是它来自的DocID,我希望能够将其更改为:
['when', 1, 2]
['yes', 1]
['', 1]
['greg', 1]
['17', 1]
删除重复项。
这是我到目前为止的内容:
for j in range(0,len(index)):
for r in range(1,len(index)):
if index[j][0] == index[r][0]:
index[j].append(index[r][1])
index.remove(index[r])
我在不断收到超出范围的错误
if index[j][0] == index[r][0]:
我认为这是因为我正在从索引中删除一个对象,所以它正在变小。 任何想法都将不胜感激(是的,我知道我不应该修改原始内容,但这只是对其进行了小规模的测试)
构建dict
/ defaultdict
会更合适吗?
就像是:
from collections import defaultdict
ar = [['when', 1],
['yes', 1],
['', 1],
['greg', 1],
['17', 1],
['when',2]]
result = defaultdict(list)
for lst in ar:
result[lst[0]].append(lst[1])
输出:
>>> for k,v in result.items():
... print(repr(k),v)
'' [1]
'yes' [1]
'greg' [1]
'when' [1, 2]
'17' [1]
是的,您的错误来自于就地修改列表。 此外,您的解决方案对于长列表而言无效。 最好改用字典,最后将其转换回列表:
from collections import defaultdict
od = defaultdict(list)
for term, doc_id in index:
od[term].append(doc_id)
result = [[term] + doc_ids for term, doc_ids in od.iteritems()]
print result
# [['', 1], ['yes', 1], ['greg', 1], ['when', 1, 2], ['17', 1]]
实际上,您可以使用range()
和len()
完成此操作。 但是,python的优点是您可以直接迭代列表中的元素而无需索引
看一下这段代码,然后尝试理解。
#!/usr/bin/env python
def main():
tot_array = \
[ ['when', 1],
['yes', 1],
['', 1],
['greg', 1],
['17', 1],
['when',2]
]
for aList1 in tot_array:
for aList2 in tot_array:
if aList1[0]==aList2[0] and aList1 !=aList2:
aList1.append(aList2[1])
tot_array.remove(aList2)
print tot_array
pass
if __name__ == '__main__':
main()
输出如下所示:
*** Remote Interpreter Reinitialized ***
>>>
[['when', 1, 2], ['yes', 1], ['', 1], ['greg', 1], ['17', 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.