从文件中读取文本并根据数字排序

时间:2016-12-04 23:27:45

标签: python python-2.7 mrjob

我有一个文本文件,说:

cat 2    
dog 4  
bird 20  
animal 3

我想阅读此文件并按此类排序(根据数字):

cat 2  
animal 3  
dog 4              
bird 20 

到目前为止尝试过的代码:

def txtsort(self, _, line):
words = [] 
    for word in WORD_RE.findall(line):
    words.append(word)
words_ini = words[0]
count_ini = np.array(words[1])
count_sort = np.sort(count_ini,axis = 0,kind='quikstart', order = None)

2 个答案:

答案 0 :(得分:2)

假设您的列表中的单词类似于:

words = [
    ('cat', 2),
    ('dog', 4),
    ('bird', 20),
    ('animal', 3)
]

result = sorted(words, key=lambda x: x[1])

答案 1 :(得分:-1)

您不需要外部库。只需拆分每一行并将其添加到列表中,将第二个元素转换为数字。然后按该元素对列表进行排序。

with open('file.txt') as f:
    result = [(a,int(b)) for line in f for a,b in line.split()]

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