我有一个包含几列的文件,例如:
PAIR 1MFK 1 URANIUM 82 HELIUM 112 2.5506
PAIR 2JGH 2 PLUTONIUM 98 POTASSIUM 88 5.3003
PAIR 345G 3 SODIUM 23 CARBON 14 1.664
PAIR 4IG5 4 LITHIUM 82 ARGON 99 2.5506
PAIR 234G 5 URANIUM 99 KRYPTON 89 1.664
现在我想做的是读取最后一列并迭代重复值,并生成一个包含两列“VALUE”和“NO OF TIMES REPEATED”
的输出文件。
我尝试过:
inp = ('filename'.'r').read().strip().replace('\t',' ').split('\n')
from collections import defaultdict
D = defaultdict(line)
for line in map(str.split,inp):
k=line[-1]
D[k].append(line)
我被困在这里了。
请帮忙。!
最佳答案
所发布的代码存在许多问题。列表理解中不允许使用 while 循环。 defaultdict 的参数应该是 list 而不是 line。这是代码的修复版本:
from collections import defaultdict
D = defaultdict(list)
for line in open('filename', 'r'):
k = line.split()[-1]
D[k].append(line)
print 'VALUE NO TIMES REPEATED'
print '----- -----------------'
for value, lines in D.items():
print '%-6s %d' % (value, len(lines))
另一种方法是使用 collections.Counter方便地对重复次数求和。这让您可以稍微简化代码:
from collections import Counter
D = Counter()
for line in open('filename', 'r'):
k = line.split()[-1]
D[k] += 1
print 'VALUE NO TIMES REPEATED'
print '----- -----------------'
for value, count in D.items():
print '%-6s %d' % (value, count)
关于python - 计算列表中值的重复次数并生成输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468153/