首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python-2:将文本文件中的行分配给变量

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

Stack Overflow用户
提问于 2016-03-03 20:21:08
回答 4查看 4.3K关注 0票数 0

我目前正试图从一个uni项目的文本文件中为竞赛制作一个记分板。

每个竞争对手都有一个competitor_no、competitor_name和3分,它们都显示在文本文件中的不同行上(因此每个竞争者的数据需要5行),例如:

1

伊莉莎·兰森

9.19

11.79

21.66

2

希希·杜兰特

17.03

7.02

17.72

我需要能把3分加起来才能得到总分,我有50个竞争对手,需要对他们进行比较,才能显示出前3名选手的号码、名字和总分。是否有将行值赋值给变量的方法?

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

代码语言:javascript
复制
 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语句,但是必须包含这个名字似乎是我的绊脚石。

有什么建议吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-03-03 21:13:20

由于您知道信息出现在文件中的顺序,所以尝试一次以5行的块读取该文件,然后相应地处理它。在下面的实现中,我将信息存储在2D列表中,然后按分数进行排序,从而获得最高的分数。

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2016-03-03 20:38:19

你可以做这样的事情(没有测试--但你明白了):基本上,每次计数到0,你就把分数保存在一个以人的名字为键的personDict中.

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2016-03-03 20:59:06

以下是我想出的:

代码语言:javascript
复制
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]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35782224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档