使用Python3对包含字符串和整数的文件进行排序

2024-04-25 20:55:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其中包含用户名及其计数,如下所示:

[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)


Tags: 用户名计数subprocess文本文件test1test2test3test4
3条回答
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())
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')

您可以使用内置函数^{}(或^{},相当于):

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']

它是如何工作的。你知道吗

引用docs

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

我将我的示例传递给lambda expression下的key参数:

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

它相当于函数:

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

此函数(或lambda)复制源字符串charsafter“:”symbol并将结果字符串强制转换为int

每次排序迭代python都会在进行比较之前调用这个函数来“cook”元素。你知道吗

相关问题 更多 >

    热门问题