繁体   English   中英

Python-2:将文本文件中的行分配给变量

[英]Python-2: Assign line in text file to a variable

我目前正在尝试通过uni项目的文本文件为比赛创建一个计分板。

每个参赛者都有一个competitor_no,competitor_name和3个分数,它们全部显示在文本文件中的不同行上(因此每个参赛者数据占用5行),例如:

1个
伊丽莎·伊安森(Eliza Ianson)
9.19
11.79
21.66
2
塞斯·杜兰特
17.03
7.02
17.72

我需要能够将3个得分相加以获得总得分。我有50个竞争对手,并且需要将它们进行比较以显示排名前3位的竞争对手,并打印出竞争对手的编号,姓名和总得分。 有没有一种方法可以将行值分配给变量?

显然,我需要一次比较5行,以便为每个单独的竞争对手获取所需的信息并处理数据,这就是我在程序中设置代码的方式。

 file = open('veggies_2014.dat')

    for line in file:

            first_place = []
            second_place = []
            third_place = []

            a = 1 
            b = 2
            c = 3
            d = 4
            e = 5

            if line == a:
                    competitor_no = line
            elif line == b:
                    competitor_name = line
            elif line == c:
                    cucumber = line
            elif line == d:
                    carrot = line
            elif line == e:
                    runner_bean = line

            a += 5
            b += 5
            c += 5
            d += 5
            e += 5

            score = float(cucumber) + float(carrot) + float(runner_bean)
            print(score)

            if score > first:
                    first = score
                    first_place.append(competitor_no)
                    first_place.append(competitor_name)
                    first_place.append(score)
            elif score > second:
                    second = score
                    second_place.append(competitor_no)
                    second_place.append(competitor_name)
                    second_place.append(score)
            elif score > third:
                    third = score
                    third_place.append(competitor_no)
                    third_place.append(competitor_name)
                    third_place.append(score)

    file.close()

    print (first_place)
    print (second_place)
    print (third_place)  

当我只处理包含数字的文件时,我可以获得分数if语句的作用,但是我似乎很be绊绊。

有什么建议么?

您可以执行以下操作(未经测试-但您知道了):基本上,每次计数为0时,您都将得分保存在personDict中,并以该人的姓名为键。

count = 0
c1_no = None;
personDict = dict()
with open("veggies_2014.dat") as f:
    score = 0
    for line in f:
        if count%5==0:
          if c1_no:
              personDict[c1_no] = score
          c1_no = line
          score = 0
       elif count%5 == 1:
          c1_name = line
       elif count%5 in (2,3,4):
           score += float(line)
       count += 1

 #now do whatever you want with the personDict..you will have something like {Emily:10} assuming Emily's scores were 2,3,5 etc

这是我想出的:

file_content = '''1
Eliza Ianson
9.19
11.79
21.66
2
Cece Durant
17.03
7.02
17.72
3
Foo Bar
10
9.5
11.2
4
Superman
7.9
12.15
9.75
'''


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    """ from http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]


users = []
for user_data in chunks(file_content.splitlines(), 5):
    user_id = int(user_data[0])
    user_name = user_data[1]
    scores = list(map(float, user_data[2:]))
    overall_score = sum(scores)

    users.append(dict(
        user_id=user_id,
        user_name=user_name,
        scores=scores,
        overall_score=overall_score
    ))


top_3 = sorted(users, key=lambda x: x['overall_score'], reverse=True)[:3]

由于您知道信息在文件中的显示顺序,因此请尝试一次以五行为单位读取文件,然后进行相应处理。 在下面的实现中,我将信息存储在2D列表中,然后按分数排序,因此您获得的分数最高。

data = []
count = 1
with open("veggies_2014.dat") as f:
    line = f.readline()
    while line and int(line) == count:
        score = 0
        entry = []
        entry.append(f.readline())   #read line with c_name
        for i in range(3):
            score += float(f.readline())     #add scores
        entry.append(score)
        data.append(entry)
        line = f.readline()
        count += 1

print(data)
data = sorted(data, key = lambda l:l[1], reverse = True)
print()
print(data)

在一些答案的帮助下,我使用了完成的代码。 尽管我选择在应用程序中将其分成不同的功能,所以可以重复使用部件。

    data = []
    count = 1

    print("")
    print("For 2014 Results please enter: veggies_2014.txt ")
    print("For 2015 Results please enter: veggies_2015.txt")
    print("For 2016 Results please enter: veggies_2016.txt ")
    fname = raw_input("Enter file name:  ")
    with open(fname) as f:
            line = f.readline()
            while line and float(line) == count:
                    score = 0
                    entry = []
                    entry.append(count)
                    entry.append(f.readline().strip())          
                    for i in range(3):
                            score += float(f.readline()) #add scores
                    score = round(score, 2)
                    entry.append(score)
                    data.append(entry)
                    line = f.readline()
                    count += 1

    data = sorted(data, key = lambda l:l[2], reverse = True)
    print("")
    final=[]

    for line in data:
            for i in line:
                    final.append(i)

我添加了此代码以更清晰地显示记分板。

    a=0
    b=3
    x=1
    for i in range(0,3):
            place=[]
            place = final[a:b]
            string = " ".join(str(x) for x in place)
            print (str(x) + ". " + string)
            a += 3
            b += 3
            x += 1

    print("")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM