【问题标题】:count for number of repetition of values in a list and generate outfile计算列表中值的重复次数并生成输出文件
【发布时间】:2012-05-15 03:19:48
【问题描述】:

我有一个包含几列的文件,例如:

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)

我被困在这里了。
请帮忙!

【问题讨论】:

  • [v for k, v in D.items() while count != -1: count += 1] 不是有效的 Python,因此会出现错误。你希望这意味着什么? count 是干什么用的?
  • 看看这个问题stackoverflow.com/questions/5505891/… on using while in list comprehensions

标签: python repeat


【解决方案1】:

发布的代码存在许多问题。列表推导中不允许使用 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)

【讨论】:

    【解决方案2】:

    现在我想做的是读取最后一列并迭代重复值并生成一个包含两列“VALUE”和“NO OF TIMES REPEATED”的输出文件。

    所以使用collections.Counter 来计算每个值出现的次数,而不是defaultdict。 (完全不清楚您要使用 defaultdict 做什么,并且无论如何您的初始化都不起作用;@ 987654324@ 是使用可创建默认值的可调用构造的。在您的情况下,默认您显然想到的值是一个空列表,因此您将使用list 来初始化defaultdict。)您不需要存储行来计算它们。 Counter 会自动为您计数。

    此外,提前处理整个文件有点难看,因为您可以直接遍历文件并获取行,这会为您完成部分处理。尽管您实际上可以在 Counter 创建中自动执行该迭代。

    这是一个完整的解决方案:

    from collections import Counter
    with open('input', 'r') as data:
        histogram = Counter(line.split('\t')[-1].strip() for line in data)
    with open('output', 'w') as result:
        for item in histogram.iteritems():
            result.write('%s\t%s\n' % item)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 2019-09-29
      相关资源
      最近更新 更多