python打印语句中的增量
我想数一数每行中的数字。作品完美,只是为了打印输出有一个小问题-我用for循环编写了一个打印语句:python打印语句中的增量,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我想数一数每行中的数字。作品完美,只是为了打印输出有一个小问题-我用for循环编写了一个打印语句: 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
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()
如果我没有误解你的意思,这是你想要的: data.txt
123
11
23
111
代码:
输出:
Counter({0: 1, 1: 1, 2: 1, 3: 1})
1 line got 1 "one"
2 line got 2 "one"
3 line got 0 "one"
4 line got 3 "one"
或者,您可以在每行中计算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)
输出:
Counter({0: 1, 1: 1, 2: 1, 3: 1})
1 line got 1 "one"
2 line got 2 "one"
3 line got 0 "one"
4 line got 3 "one"
在编写此程序之前,您确实必须阅读有关列表的内容。counts=[0]*17,然后counts[count]+=1。删除所有if/elif语句。print语句呢?如果我想打印for循环中的所有计数值no,我想在for循环中设置我的计数,以获得count1、count2的计数值,所以on@hassan在我的例子中,{0:1,1:1,2:1,3:1}不是你想要的吗?你想对count1做什么,count2@McGragy我想给count0,count1。。。使用loop@hassan实际上,我认为这不是一个好主意,如果你的数据很大,你不能分配这么多变量,如果你想要{0:1,1:1,2:1,3:1},你可以遍历这个dict-to-print语句。