如何获得正确的数量count()在两行,为2个单独的团队? (计数目标) [英] How do I get the right amount of count() on two lines, for 2 separate teams? (counting goals)

查看:277
本文介绍了如何获得正确的数量count()在两行,为2个单独的团队? (计数目标)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写的代码,应该读取一个文本文件,并检查多少次,'EASTS'或'WESTS'得分,我可以通过使用find和'EASTS'来获取数字'WESTS'。
但是不是得到发生,我得到它在每一行中存在多少次。



因此:

  1 
1 $ b b 1
1

(和idk为什么在1之前有空格属于wests')



这里是文本:

  EASTS与WESTS 
EASTS已取得25:13
WESTS已取得26:38
WESTS已取得40:23
WESTS已取得42:01



这里是我的代码,我做错了什么?

 code> name =scores.txt

打开(名称)为f:
ff = f.readlines()[1:]
ff:
words = line.split()
a = words.count('EASTS')
b = words.count('WESTS')
a_ = str b $ b b_ = str(b)
eas = a_.strip('0')
wes = b_.strip('0')
print(eas,wes)

结果应如下所示:

  WESTS 3 
EASTS 1

有人可以帮忙吗?提前感谢!

解决方案

初始化变量( wests easts )为0.在循环中递增1。打印结果。

  import itertools 

team1,team2 ='WESTS','EASTS'
count1,count2 = 0,0
with open('scores.txt')as f:
对于itertools.islice中的行(f,1,None):
如果行。 startswith(team1):
count1 + = 1
else:
count2 + = 1
print(team1,count1)
print(team2,count2)



在运行时获取团队名称



 code> with open('scores.txt')as f:
team1,_,team2 = next(f).split()
count1,count2 = 0,0
for f:
if line.startswith(team1):
count1 + = 1
else:
count2 + = 1
print(team1,count1)
print(team2,count2)


The code I'm trying to write, is supposed to read a text file, and check how many times, 'EASTS', or 'WESTS' have scored, I can fetch the numbers by using find and 'EASTS' or 'WESTS'. But instead of getting the occurrence, I get how many times it exists in each line.

So:

1 
 1
 1
 1

(and idk why there is space before the 1's that belong to the wests')

Here is the text:

EASTS versus WESTS
EASTS have scored 25:13
WESTS have scored 26:38
WESTS have scored 40:23
WESTS have scored 42:01

And here is my code, what am I doing wrong?

name = "scores.txt"

with open(name) as f:
    ff = f.readlines()[1:]
    for line in ff:
        words = line.split()
        a = words.count('EASTS')
        b = words.count('WESTS')
        a_ = str(a)
        b_ = str(b)
        eas =  a_.strip('0')
        wes =  b_.strip('0')
        print(eas, wes)

The result should look something like this

WESTS 3
EASTS 1

Can somebody help? Thank you in advance!

解决方案

Initialize variables (wests, easts) as 0. Increment 1 in a loop. Print result.

import itertools

team1, team2 = 'WESTS', 'EASTS'
count1, count2 = 0, 0
with open('scores.txt') as f:
    for line in itertools.islice(f, 1, None):
        if line.startswith(team1):
            count1 += 1
        else:
            count2 += 1
    print(team1, count1)
    print(team2, count2)

Get team names at runtime

with open('scores.txt') as f:
    team1, _, team2 = next(f).split()
    count1, count2 = 0, 0
    for line in f:
        if line.startswith(team1):
            count1 += 1
        else:
            count2 += 1
    print(team1, count1)
    print(team2, count2)

这篇关于如何获得正确的数量count()在两行,为2个单独的团队? (计数目标)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆