簡體   English   中英

Python異常文件排序

[英]Python unusual file sorting

我有一個txt文件包含以下方式的數據:

23       1      65      15      19.2
19       2      66      25      25.7
10       3      67      35      16.5
100      4      68      45      10.4
20       5      69      55      6.8
201      6      64      65      9.2

在文件中,每個值都使用\\ t與其他值分開,然后\\ n用於下一行。

我想根據每行的第一個值對此文件進行排序。 我的預期輸出是:

10       3      67      35      16.5
19       2      66      25      25.7
20       5      69      55      6.8
23       1      65      15      19.2
100      4      68      45      10.4
201      6      64      65      9.2

但我得到的實際輸出是:

10       3      67      35      16.5
100      4      68      45      10.4
19       2      66      25      25.7
20       5      69      55      6.8
201      6      64      65      9.2
23       1      65      15      19.2

它將值作為字符串,因此不將整數值作為整數。 我試過解析,但它無法正常工作。

我的代碼:

with open('filename.txt') as fin:
        lines = [line.split() for line in fin]
lines.sort(key=itemgetter(0),reverse=True)

with open('newfile.txt', 'w') as fout:
    for i in lines:
            fout.write('{0}\t\t\t\t\n'.format('\t\t\t '.join(i)))

請盡可能幫助。

您當前正在比較字符串,您需要比較整數:

lines.sort(key=lambda x:int(x[0]), reverse=True)

字符串按字典順序進行比較,因此:

>>> '2' > '100'
True

轉換為int修復此問題:

>>> int('2') > int('100')
False

另外看一下大熊貓 ,如果你以后飛機做更復雜的操作,例如:

import pandas as pd

pd.read_table('filename.txt', header=None)\
            .sort(columns=0)\
            .to_csv('newfile.txt', sep='\t', header=None, index=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM