簡體   English   中英

在python3中對包含字符串和整數的文件進行排序

[英]To sort a file which contains both strings and integers in python3

我有一個文本文件,其中包含用戶名及其數量,如下所示:

[test1]:11
[test2]:1097
[test3]:461
[test4]:156
[test5]:16
[test6]:9
[test7]:568
[test8]:17
[test9]:373
[test10]:320

我想按降序對輸出進行排序,輸出應如下所示:

[test2]:1097
[test7]:568
[test3]:461
[test9]:373
[test10]:320
[test4]:156
[test8]:17
[test5]:16
[test1]:11
[test6]:9

請幫助我在python3中實現這一目標。

我試圖這樣做..這是行不通的。

subprocess.Popen(['sort', '-n', '-r', 'Test.txt'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

data = '''[test1]:11
[test2]:1097
[test3]:461
[test4]:156
[test5]:16
[test6]:9
[test7]:568
[test8]:17
[test9]:373
[test10]:320'''

for line in sorted(data.splitlines(), key=lambda k: int(k.split(':')[-1]), reverse=True):
    print(line)

打印:

[test2]:1097
[test7]:568
[test3]:461
[test9]:373
[test10]:320
[test4]:156
[test8]:17
[test5]:16
[test1]:11
[test6]:9

編輯:從文件中讀取可以執行以下操作:

with open('Test.txt', 'r') as f_in:
    for line in sorted(f_in.readlines(), key=lambda k: int(k.split(':')[-1]), reverse=True):
        print(line.strip())

您可以使用內置函數sorted() (或list.sort() ):

s = """[test1]:11
[test2]:1097
[test3]:461
[test4]:156
[test5]:16
[test6]:9
[test7]:568
[test8]:17
[test9]:373
[test10]:320"""
lst = s.splitlines()
sorted_lst = sorted(lst, key=lambda item: int(item[item.index(":") + 1:]), reverse=True)
print(sorted_lst)

輸出:

['[test2]:1097', '[test7]:568', '[test3]:461', '[test9]:373', '[test10]:320', '[test4]:156', '[test8]:17', '[test5]:16', '[test1]:11', '[test6]:9']

它是如何工作的

引用文檔

list.sort()sorted()都有一個關鍵參數,用於指定在進行比較之前在每個列表元素上要調用的函數。

在我的示例中,我將下一個lambda表達式傳遞給key參數:

lambda item: int(item[item.index(":") + 1:])

它等效於功能:

def func(item):
    return int(item[item.index(":") + 1:])

這個函數(或lambda)從源字符串復制字符 “:”符號和投結果字符串為int。

每次排序迭代python都會在進行比較之前將該函數調用為“ cook”元素。

res =[]
with open('result.txt') as f:
    tmp=[]
    for i in f.readlines():
        tmp=i.strip('\n').split(':')
        res.append(tmp)

sol = sorted(res, key=lambda x:x[1])
with open('solution.txt','a+') as f:
    for i in sol:
        f.write(r'{}:{}'.format(i[0],i[1])+'\n')

嘗試這個,

with open('file1.txt','r') as f:
    print(sorted([line.replace('\n','') for line in f], key = lambda x:int(x.replace('\n','').split(':')[-1]), reverse=True))

輸出:

['[test2]:1097', '[test7]:568', '[test3]:461', '[test9]:373', '[test10]:320', '[test4]:156', '[test8]:17', '[test5]:16', '[test1]:11', '[test6]:9']

注意:

它將取代換行符( \\n與空字符串)( ''

def dict_val(x):
...     return x[1]

###First Read the File
f = open('test.txt','r')
content = f.readlines()

# Now add contents of file to a dict
count_dict = {}
for line in content:
...     key,value = line.split(':')
...     count_dict[key] = value

### Now using sorted function to sort values.
sorted_x = sorted(count_dict.items(), key=dict_val)
print(sortex_x)


我們需要使用-k選項指定要進行排序的字段。 有關更多詳細信息,請參閱鏈接: https : //unix.stackexchange.com/questions/77406/sort-only-on-the-second-column

Code

import subprocess
process = subprocess.Popen(['sort', '-n', '-r', '-t:', '-k2,2', 'input.txt'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # start index 2 and end index =2 for sroting
stdout = process.communicate()[0]
print(stdout.decode('utf-8'))

Output

[test2]:1097
[test7]:568
[test3]:461
[test9]:373
[test10]:320
[test4]:156
[test8]:17
[test5]:16
[test1]:11
[test6]:9

暫無
暫無

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

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