如何从文本文件中搜索键内的顶部和底部2个数字?

时间:2016-05-12 23:05:12

标签: python

到目前为止,我的代码一无所获,因为我根本不知道该怎么做:

f = open ("players.txt","r")
fileinfo = f.readlines()
f.close()

....

文本文件:

Joe,Bloggs, 2, 9, 0, 0, 
Sarah,Brown, 2, 12,  0, 0, 
Andrew,Smith, 2, 4, 0, 0, 
Ray,Charles, 2, 4, 0, 0, 
Kevin,White, 2, 0, 2, 0, 
Samantha,Collins, 2, 1, 0, 0, 

因此,代码的目的是选择字符串[2]中的最低和最高2分。

E.g。莎拉和乔是最高的,然后凯文和萨曼莎是最低的两个。

前两个人的字符串[2]会减少一个,而最低的两个会增加他们的字符串[2]。

E.g。

Joe,Bloggs, 1, 9, 0, 0, 
Sarah,Brown, 1, 12,  0, 0,
......
...... 
Kevin,White, 3, 0, 2, 0, 
Samantha,Collins, 3, 1, 0, 0, 

2 个答案:

答案 0 :(得分:1)

我通常会建议您学习熊猫。但我认为这个问题太先进了。 因此,我建议使用类作为抽象来存储每行的数据。 然后对数据进行排序,这样您就不必自己处理找到最小值和最大值。 然后只需获取第一个和最后一个项目,然后递增或递减所需的值。

class Player(object):
    def __init__(self,fname,lname,number1, number2, number3, number4, extraField):
        self.fname = fname
        self.lname = lname
        self.number1 = int(number1)
        self.number2 = int(number2)
        self.number3 = int(number3)
        self.number4 = int(number4)
    def increase_number2(self):
        self.number2+=1
    def decrease_number2(self):
        self.number2-=1

f = open ("players.txt","r")
players = []
for eachLine in f.readlines():
    columns = eachLine.split(",")
    newPlayer = Player(*columns)
    players.append(newPlayer)
f.close()
players = sorted(players, key = lambda x: x.number2)
topPlayer = players[-1]
topPlayer.increase_number2()
print topPlayer.fname,topPlayer.number2
secondPlayer = players[-2]
lowestPlayer = players[0]
nextToLastPlayer = players[1]

答案 1 :(得分:1)

你走了。 zip(range(..), lines)为每行添加行号,结果如下:

[0, [Joe, ...]],
[1, [Sarah, ...]],
...

然后我们按字符串[3]对其进行排序,可以通过lambda x: x[1][3]

进行访问

然后更新原始行,并写入文件。

f = open('players.txt', 'r')
lines = []
for line in f.readlines():
    line = [x.strip() for x in line.split(',')]
    line[2] = int(line[2])
    line[3] = int(line[3])
    lines.append(line)
f.close()

ordered = sorted(zip(range(len(lines)), lines), key=lambda x: x[1][3])
lines[ordered[-1][0]][2] -= 1
lines[ordered[-2][0]][2] -= 1
lines[ordered[0][0]][2] += 1
lines[ordered[1][0]][2] += 1

with open('players2.txt', 'w') as f:
    for line in lines:
        line = [str(x) for x in line]
        f.write(', '.join(line) + '\n')