File Sorting in Python

后端 未结 3 704
-上瘾入骨i
-上瘾入骨i 2021-01-29 07:57

I would like to sort a file in Python based on numerical values:

My input file looks like this:

66135 - A
65117 - B
63301 - C
63793 - D

相关标签:
3条回答
  • 2021-01-29 08:31

    Here is a complete code for that.

    with open('inputFileName') as fp:
        lst = map(lambda s:s.rstrip(), fp.readlines())
    
    with open('outputFileName', 'w') as fp:
        fp.write("\n".join(sorted(lst, key=lambda s:int(s.split()[0]))))
    
    0 讨论(0)
  • 2021-01-29 08:36
    f2.writelines(sorted(f1, key=lambda line:int(line.split()[0])))
    

    where f2 is your output file and f1 is your input file.

    0 讨论(0)
  • 2021-01-29 08:36

    you can try this way

    with open('filename','r') as file:
        # spilt() the line with '-'
        lis=[line.strip().split('-') for line in file]
        # sort the lis using the values
        print sorted(lis,key=lambda x:int(x[0].strip()))
    
    0 讨论(0)
提交回复
热议问题