python - 如何在字符的最后一个实例之后对文本文件进行排序?

标签 python python-3.x list dictionary

目标:根据最后一个斜杠之后出现的字符按字母顺序对文本文件进行排序。请注意,最后一个斜杠之前有随机数字。

文本文件的内容:

https://www.website.com/1939332/delta.html
https://www.website.com/2237243/alpha.html
https://www.website.com/1242174/zeta.html
https://www.website.com/1839352/charlie.html

期望的输出:

https://www.website.com/2237243/alpha.html
https://www.website.com/1839352/charlie.html
https://www.website.com/1939332/delta.html
https://www.website.com/1242174/zeta.html

代码尝试:

i = 0
for line in open("test.txt").readlines(): #reading text file
    List = line.rsplit('/', 1)            #splits by final slash and gives me 4 lists
    dct = {list[i]:list[i+1]}             #tried to use a dictionary 
    sorted_dict=sorted(dct.items())       #sort the dictionary

textfile = open("test.txt", "w")
for element in sorted_dict:
    textfile.write(element + "\n")
textfile.close()
   

代码不起作用。

最佳答案

我会将不同的 key 函数传递给 sorted功能。例如:

with open('test.txt', 'r') as f:
    lines = f.readlines()
    lines = sorted(lines, key=lambda line: line.split('/')[-1])

with open('test.txt', 'w') as f:
    f.writelines(lines)

参见here了解关键功能的更详细说明。

关于python - 如何在字符的最后一个实例之后对文本文件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72178137/

相关文章:

使用深度名称向量作为索引替换嵌套列表

python - 如何为 REST Api 功能设置 Python

python - Apache Spark 中的高效字符串匹配

python - 使用 PIL 将图像保存为压缩的 TIFF 时出现 OSError

Python反向字典项目顺序

Python:列表索引必须是整数,而不是元组

python - 以秒为单位的时间差(作为 float )

python - 如何向列表的每个值添加一个字符串,然后将该字符串的值加起来?

python - 读取文件时字符串索引超出范围

python - 从文本文件中读取列表的元组作为元组,而不是字符串 - Python