File Sorting in Python

后端 未结 3 702
-上瘾入骨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: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()))
    

提交回复
热议问题