文本文件中从最高到最低?

时间:2015-04-04 11:17:08

标签: python

我是python的新手,我一直在尝试以从高到低的形式打印出一个得分列表。得分列表保存在文本文件中,并按此设置......

Jax:6
Adam:10 
Rav:2 

我看过书,但我没有去过任何地方,有没有人知道如何从文本文件中以最高到最低的形式接收分数。谢谢。

我使用的是Python 3.3.2版本。

4 个答案:

答案 0 :(得分:1)

尝试这样:

with open("your_file") as f:
    my_dict = {}
    for x in f:
        x = x.strip().split(":")
        my_dict[x[0]] = x[1]

    print sorted(my_dict.items(), key= lambda x:x[1], reverse=True)

答案 1 :(得分:1)

首先,您需要加载文件(假设它的名称是file.txt),然后您需要读取值,然后对其进行排序然后打印。它并不像看起来那么困难。

仅在得分唯一时才适用

# init a dictionary where you store the results
results = {}
# open the file with results in a "read" mode
with open("file.txt", "r") as fileinput:
    # for each line in file with results, do following
    for line in fileinput:
        # remove whitespaces at the end of the line and split the line by ":"
        items = line.strip().split(":")
        # store the result, the score will be the key
        results[int(items[1])] = items[0]
# sort the scores (keys of results dictionery) in descending order
sorted_results = sorted(results.keys(), reverse=True)

# for each score in sorted_results do the following
for i in sorted_results:
    # print the result in the format of the scores in your file 
    print "{}:{}".format(results[i],i)

示例代码中解释了这些步骤。

相关文档或示例的链接如下:

修改

即使分数值相同,此版本也能正常运行。 (感谢@otorrillas指出问题)

# init a list where you store the results
results = []
# open the file with results in a "read" mode
with open("file.txt", "r") as fileinput:
    # for each line in file with results, do following
    for line in fileinput:
        # remove whitespaces at the end of the line and split the line by ":"
        items = line.strip().split(":")
        # store the result as a list of tuples
        results.append(tuple(items))

# first it sorts all the tuples in `results` tuple by the second item (score)
# for each result record in sorted results list do the following
for result_item in sorted(results, key=lambda x: x[1], reverse=True):
    # print the result in the format of the scores in your file 
    print "{}:{}".format(result_item[0], result_item[1])

代码中的注释描述了代码。主要区别在于代码不再使用dict并使用tuple代替。它还使用按键排序。

答案 2 :(得分:1)

只是为了好玩:如果您只需要对文件中的数据进行排序,则可以使用UNIX sort命令

sort -k 2 -t : -n -r $your_file

(参数是:按第二个键排序,按'排序字段:',数字排序,反向顺序)。

答案 3 :(得分:0)

tldr

sorted([l.rstrip().split(':') for l in open('d.d')], key=lambda i:int(i[1]))

您需要对文件中的行进行操作,您可以简单地将其作为

[l for l in open('FILE')]

但可能没有新行

[l.rstrip() for l in open('FILE')]

并最终分割为:冒号字符

[l.rstrip().split(':') for l in open('FILE')]

这样您就获得了一份清单

>>> print [l.rstrip().split(':') for l in open('FILE')]
[['Jax', '6'], ['Adam', '10'], ['Rav', '2']]

这是你想要排序的东西。 物种 你想根据第二个字段的数值

对它进行排序
>>> print [int(r[1]) for r in [l.rstrip().split(':') for l in open('FILE')]]
[6, 10, 2]

sorted内置函数接受可选参数key,这是一个函数,用于提取要在可排序的iterable的每个元素中进行比较的部分

>>> sd = sorted([l.rstrip().split(':')for l in open('FILE')],key=lambda r:int(r[1]))
>>> print sd
[['Rav', '2'], ['Jax', '6'], ['Adam', '10']]

那是所有人......