按分隔符分隔的数字值按升序对文件进行排序

时间:2015-01-01 19:18:45

标签: python

我有一个文件,其中每一行的格式如下:string,number

例如:

whats up, 843

peace out, 23

hello, 91

hi, 11

see ya later, 5

我想按照逗号右侧的数字值按升序排序文件。

例如:

see ya later, 5

hi, 11

peace out, 23

hello, 91

whats up, 843

我知道在python中你可以使用sorted()方法按升序对数字列表进行排序,但我不确定如何在逗号的右侧提取数字并对文件进行排序。

3 个答案:

答案 0 :(得分:0)

您可以使用sorted()

>>> s="""whats up, 843
... 
... peace out, 23
... 
... hello, 91
... 
... hi, 11
... 
... see ya later, 5"""

>>> l=[i for i in s.split('\n') if i]
>>> l
['whats up, 843', 'peace out, 23', 'hello, 91', 'hi, 11', 'see ya later, 5']
>>> print '\n'.join(sorted(l,key=lambda x : int(x.split()[-1])))
see ya later, 5
hi, 11
peace out, 23
hello, 91
whats up, 843

答案 1 :(得分:0)

你拥有的是元组列表。您可以使用与this question类似的解决方案进行最终排序。但是,您首先需要将数据文件放入此元组列表中。

data = []
for line in open('test.txt'):
    data.append((line.split(",")[0].strip(),int(line.split(",")[1].strip())))

data.sort(key=lambda x: x[1])

print data

在每一行中读取的内容,并将其拆分为逗号(,)。第一个元素周围的额外空格被剥离,第二个元素被转换为整数。然后,我们对列表进行排序。

这将输出以下列表:

[
    ('see ya later', 5), 
    ('hi', 11), 
    ('peace out', 23), 
    ('hello', 91), 
    ('whats up', 843)
]

答案 2 :(得分:0)

要使用已排序,它将被排序(dict1,key = dict1.get)

如果你打印它,就像我在下面所做的那样,它应该可以正常工作。

def test():
    testList = {"whats up": 843, "peace out": 23, "hello": 91, "hi": 11, "see ya later": 5}
    print(sorted(testList, key=testList.get))
相关问题