Python根据元素内容重新排列列表的顺序

2024-03-28 16:37:05 发布

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

我有一个文件名列表,目前按“文件类别”排序,例如:

list = ['categorya.1.file','categorya.2.file','categoryb.1.file','categoryc.1.file']

可能的类别数目是任意的。给定类别中的文件数是任意的。你知道吗

我希望重新排列列表,以便它每次读取一个类别。因此,上述列表将重新排列为:

newlist = ['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file', 'categorya.1.file']

这些列表的长度可能会很长,所以我认为效率是关键。最好的方法是什么?你知道吗


Tags: 文件方法列表排序文件名类别list关键
2条回答

下面的内容看起来比实际情况更糟—它只是使用groupby按类别将列表分解为列表,然后使用roundrobin将这些列表合并为单个列表。你知道吗

使用itertools:

from itertools import groupby, islice, cycle

# The following is from the itertools recipes 
# but it has had its splot removed for simplicity
def roundrobin(iterables):
    "roundrobin('ABC', 'D', 'EF')  > A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

test_list = ['categorya.1.file','categorya.2.file','categoryb.1.file','categoryc.1.file']
new_list = list(roundrobin(list(list(l) for (c, l) in groupby(test_list, lambda v: v.split('.')[0]))))
print new_list

印刷品:

['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file', 'categorya.2.file']

您只需按转换为int的数字进行排序,使用最后一个字母打破关系:

lst = ['categoryc.2.file','categorya.1.file','categorya.2.file',
       'categoryb.2.file','categoryb.1.file','categoryc.1.file']

def key(x):
    spl = x.split(".",2)
    return int(spl[1]),spl[0][-1]
lst.sort(key=key)

输出:

['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file',
'categorya.2.file', 'categoryb.2.file', 'categoryc.2.file']

如果您不关心类别分组后的顺序,那么只需使用int

lst = ['categoryc.2.file','categorya.1.file','categorya.2.file',
       'categoryb.2.file','categoryb.1.file','categoryc.1.file']

lst.sort(key=lambda x: int(x.split(".",2)[1]))

print(lst)
['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file', 
'categoryc.2.file', 'categorya.2.file', 'categoryb.2.file']

.sort已就位,因此不需要创建任何其他列表。你知道吗

相关问题 更多 >