Python-按数字对字符串进行排序 [英] Python - sorting strings numerically

查看:125
本文介绍了Python-按数字对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python将两个文件合并在一起以创建一个新文件,两个文件中的数据在我要排序的每个字符串的开头都有一个ID,因此它们的顺序相同并且可以合并.为此,我使用了.sort(),以便它们都以相同的顺序排列,并且注释与细节匹配.但是,我现在想对它们重新排序,以使它们变为1、2、3、4 ...,而不是1、10、100、1000、1001、1002等,但是由于数字是开始,所以我遇到了困难字符串和python不会将字符串的前四个字符转换为整数.如果有帮助,它也是制表符分隔的文件,并且ID后的下一条信息是日期.

I'm using python to merge two files together to create a new one, the data in both files have an id at the start of every string which I want to sort so they're both in the same order and can be merged. To do this I've used .sort() so that they're both arranged in the same order and the comments match the details. However, I'd now like to reorder them so that they go 1, 2, 3, 4... instead of 1, 10, 100, 1000, 1001, 1002 etc but I am having difficulties since the number is the start of a string and python wont convert the first four characters of a string to an integer. If it is any help it is also a tab delimited file and the next piece of information after the id is the date.

任何想法都会受到赞赏,理想情况下,我不想导入任何库.

Any ideas would be appreciated and ideally I would not like to import any libraries.

我的代码是:

comments = R'C:\Pythonfile\UFOGB_Comments.txt'
details = R'C:\Pythonfile\UFOGB_Details.txt'
mydest = R'C:\Pythonfile\UFOGB_sorted.txt'

with open(details,'rt') as src:
    readdetails = src.readlines()
    readdetails.sort()

with open(comments,'rt') as src:
    readcomments = src.readlines()
    readcomments.sort()

with open(mydest, 'w') as dest:
    for i in range(len(readdetails)):
        cutcomm = readcomments[i][readcomments[i].find('"'):]
        dest.write('{}\t{}'.format(readdetails[i].strip('\n'),cutcomm))

推荐答案

您可以尝试使用以下方法将第一个字段解析为int

You could try to parse the first field as int with:

readdetails.sort(key=lambda x: int(x.split()[0]))

如果所有行的格式都一致,这将很好地工作.

This will work well if all lines are in a consistent format.

否则,将更复杂的函数用作list.sort()的关键函数,例如:

Otherwise use a more complex function as a key function for list.sort(), e.g.:

def extract_id(line):
    # do something with line
    # and return an integer, or another kind of value

并将其传递给sort函数:

and pass it to sort function:

readdetails.sort(key=extract_id)

这篇关于Python-按数字对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆