python print语句中的增量

时间:2017-03-12 05:21:28

标签: python python-2.7 python-3.x

我想计算每行中的数量。作品完美,只有一个小问题才能打印输出 - 我用for循环写了一个print语句:

k=0
for k in range(0,17):
 print ("Number of %d ="  %(k)) , count+k
i=0
k=0

我拥有的计数器名称是count0, count1,.....所以

我想将count0,count1 ...赋予带循环的print语句,因为如果我写 countk 肯定会将它作为单个变量, 如何通过循环增加计数器。

#!/usr/bin python
import sys
f=open('data-hist.txt','r')

num_lines=21
countnew=0
count0,count1,count2,count3,count4,count5,count6,count7,count8,count9,count10,count11,count12,count13,count14,count15,count16=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

i=0
while i < num_lines:
  line=f.readline()
  count=line.count('1')

  if (count==0):
   count0=count0+1
  elif(count==1):
   count1=count1+1
  elif(count==2):
   count2=count2+1
  if (count==3):
   count3=count3+1
  elif(count==4):
   count4=count4+1
  elif(count==5):
   count5=count5+1 
  if (count==6):
   count6=count6+1
  elif(count==7):
   count7=count7+1
  elif(count==8):
   count8=count8+1 
  if (count==9):
   count9=count9+1
  elif(count==10):
   count10=count10+1
  elif(count==11):
   count11=count11+1
  if (count==12):
   count12=count12+1
  elif(count==13):
   count13=count13+1
  elif(count==14):
   count14=count14+1  
  elif (count==15):
   count15=count15+1
  elif (count==16):
   count16=count16+1

  #print count16
  i+=1
k=0
for k in range(0,17):
 print ("Number of %d ="  %(k)) , count+k
i=0
k=0
sys.exit()

1 个答案:

答案 0 :(得分:2)

如果我不误解你的意思,这就是你想要的:

data.txt中

123
11
23
111

代码:

from collections import Counter

with open("data.txt") as f:
    print(Counter([Counter(i)['1'] for i in  f.readlines()]))

输出:

Counter({0: 1, 1: 1, 2: 1, 3: 1})

或许你想在每一行中计算1:

来自集合导入计数器

with open("data.txt") as f:
    for k,v in {num: Counter(i)['1'] for num, i in enumerate(f.readlines())}.items():
        print "{0} line got {1} one".format(k+1,v)

输出:

1 line got 1 "one"
2 line got 2 "one"
3 line got 0 "one"
4 line got 3 "one"