问题陈述
我有以下文件(文件按所有三列排序):
D000001 D000001 1975
D000001 D000001 1976
D000001 D002413 1976
D000001 D002413 1979
D000001 D002413 1987
D000001 D004298 1976
D000002 D000002 1985
D000003 D000900 1975
D000003 D000900 1990
D000003 D004134 1983
D000003 D004134 1986
我需要计算重复对(在第1列和第2列中),并为每对这样的对分配第3列中的最小值。对于我的玩具文件,输出应该是:
^{pr2}$我的问题
我对电流输出的初步尝试如下。在
^{3}$电流输出:
D000001 D000001 (2, 1976) ## Should be 1976 etc.
D000001 D002413 (3, 1987)
D000001 D004298 (1, 1976)
D000002 D000002 (1, 1985)
D000003 D000900 (2, 1990)
D000003 D004134 (2, 1986)
由于文件很大,不应使用内存字典来管理数据。开始读取源文件并将结果直接输出到目标文件,您只需要3个变量
一个存储当前元组,第二个存储计数,第三个存储最高值。当元组更改时,将值写入输出文件并继续。在
这一个将有非常小的内存占用和可以处理疯狂的大文件以及。但当然,这只会因为元组是排序的。在
Groupby和generators之路:
NB:这个解决方案是一个python3.x解决方案,其中}返回迭代器,而不是像python2.x中那样返回{}
filter
和{解决方案:
输出:
^{pr2}$讨论:
实际的算法与itertools.groupby非常相似(请参阅使用此方法的另一个答案,但假设Python3.x)。在
可能值得注意的是,这个实现也是``O(n`)(Big O)。在
相关问题 更多 >
编程相关推荐