对不一致元素列表的最后一个元素进行排序

时间:2014-08-06 16:42:04

标签: python sorting

简介

跟进this question

目标:对不一致数量的元素列表的最后一个元素进行排序

方法

代码

import os

cwd = os.getcwd()

for fn in os.listdir(cwd):
    print(fn)

    with open(fn, "r+") as f, open(cwd + "\\all.txt", "r+") as f2:
        lines = sorted(f, key=lambda text: text.split('-', 1)[::-1])
        print(lines)

        my_new_list = [fn + " - " + x for x in lines]
        print (my_new_list)

        f2.write("\n".join(my_new_list))

示例

aa - http://cc
bb - http://bb
cc - http://aa
aa - aa - http://cc
bb - bb - http://bb
cc - cc - http://aa
aa - aa - aa - http://cc
bb - bb - bb - http://bb
cc - cc - cc - http://aa

输出

列表未按最后一个元素排序。似乎排序发生在第二个元素上。

电流

sample.txt - aa - aa - aa - http://cc

sample.txt - aa - aa - http://cc

sample.txt - bb - bb - bb - http://bb

sample.txt - bb - bb - http://bb

sample.txt - cc - cc - cc - http://aa
sample.txt - cc - cc - http://aa

sample.txt - cc - http://aa

sample.txt - bb - http://bb

sample.txt - aa - http://cc

预期

sample.txt - cc - http://aa
sample.txt - cc - cc - http://aa
sample.txt - cc - cc - cc - http://aa

sample.txt - bb - http://bb
sample.txt - bb - bb - http://bb
sample.txt - bb - bb - bb - http://bb

sample.txt - aa - http://cc
sample.txt - aa - aa - http://cc
sample.txt - aa - aa - aa - http://cc

2 个答案:

答案 0 :(得分:3)

您的问题是text.split('-', 1),它只会将字符串拆分一次(在第一个 '-')。

您实际上想要拆分 last '-'所以您想要text.rsplit('-', 1)

*注意,rsplit,而不是split: - )

答案 1 :(得分:1)

要根据最后一个元素进行排序,您可以像这样使用str.rsplit

lines = sorted(f, key=lambda text: text.rsplit('-', 1)[1])