无法添加fi中的数字

2024-09-30 18:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有问题。 1-黄金 2-银色 3-青铜

我想做的是计算每年获得多少块金牌。例如,在2002年,共有2枚金牌、1枚银牌和1枚铜牌。你知道吗

代码:

def main():
    year = str(input("Enter year to count its winners: "))
    goldmedal = 0
    openFile = open("test.txt")
    gold = "1"
    for line in openFile.read().split('\n'):
        if year in line:
            if str(1) in line:
                goldmedal = goldmedal + 1   
    print("Gold Medals: ", gold medal)

预期产量:

Enter year to count its winners: 2002
Gold Medals: 2

文本文件:

WHEELER
ADAM
2001
3

KHUSHTOV
ASLANBEK
2002
1

LOPEZ
MIJAIN
2002
1

BAROEV
KHASAN
2002
2

BAROEV
KHASAN
2002
3

Tags: to代码inifcountlineyearits
3条回答

一个简单的修复程序将使用迭代器并请求下一行:

lines = iter(openFile.read().split('\n'))
for line in lines:
    if year in line:
        line = next(lines)
        if str(1) in line:
            goldmedal = goldmedal + 1 

一个合适的解决方案是用'\n\n'分割块,并将这些块作为一组关于某个奖牌的数据进行处理。你知道吗

此代码是一个错误(tm)修复程序—它假定数据是正确的,并在找到正确的年份时设置标志。这不是一个好的解决方案:更好的解决方案(在我看来)是先将数据加载到数据结构中(可能是一个字典),然后搜索字典

from __future__ import print_function
def main():
    year = str(input("Enter year to count its winners: "))
    goldmedal = 0
    found_year = False
    openFile = open("test.txt")
    gold = "1"
    for line in openFile.read().split('\n'):
        if year in line:
            found_year = True
            continue:

        if found_year:
            if gold in line:
                goldmedal = goldmedal + 1
            found_year = False  

print("Gold Medals: ", goldmedal)

更好的解决方案是:

from __future__ import print_function
def main():
    winners = []
    with open("test.txt") as openfile:
         surname, firstname, year, medal, blank = next(openfile), next(openfile), next(openfile), next(openfile), next(openfile)
         winners.append({"Surname":surname,"Firstname":firstname,"Medal":medal})

   year = str(input("Enter year to count its winners: "))
   goldcount = sum([1 for winner in winners if winner.year=year and medal=1])
   print ("Gold Medals", goldcount)

注意:这些应该是好的,但我也没有测试。你知道吗

>>> import re # Import regular expression python module
>>> with open('in','r') as f:  # Open the file
...     text = f.read()        # Read the contents
# Get all the years based on the regular expression, which in this case is extracts all the 4 digits and 1 digit numbers seperated by `\n` 
>>> values = re.findall(r'([0-9]{4})\n([0-9]{1})', text) 
>>> values
[('2001', '3'), ('2002', '1'), ('2002', '1'), ('2002', '2'), ('2002', '3')]
>>> a = raw_input('Enter year to count its winners:')  # Input
>>> b = '1' 
>>> j=(a,b) # create this tuple based on your query 
>>> output = sum([ 1 for i in year_count if i==j]) # Get the total gold for that year 
>>> print 'Gold Medals: ',output  # Output

相关问题 更多 >