hassan - 1 year ago 102
Python Question

# Increment in the python print statement

I want to count number of ones in the each line. The works perfect, just have one small issue in order to print the output - I wrote one print statement with for loop:

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

The counter names I have are
`count0, count1`
,.....so on

I want to give
`count0,count1`
... to the print statement with the loop, because if I write countk definitely it will take it as a single variable,
How can I increment the counter with the loop.

``````#!/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:
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()
``````

If I don't misunderstand your meaning,is this you want:

data.txt

``````123
11
23
111
``````

Code:

``````from collections import Counter

with open("data.txt") as f:
``````

Output:

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

Or maybe you want to count 1 in each line:

from collections import Counter

``````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)
``````

Output:

``````1 line got 1 "one"
2 line got 2 "one"
3 line got 0 "one"
4 line got 3 "one"
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download