Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python根据元素内容重新排列列表的顺序_Python_List - Fatal编程技术网

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

Python根据元素内容重新排列列表的顺序,python,list,Python,List,我有一个文件名列表,目前按“文件类别”排序,例如: list = ['categorya.1.file','categorya.2.file','categoryb.1.file','categoryc.1.file'] 可能的类别数量是任意的。给定类别中的文件数是任意的 我希望重新排列列表,使其每次读取一个类别。因此,上述列表将重新排列为: newlist = ['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file', 'cate

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

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

这些列表的长度可能非常长,所以我认为效率是关键。最好的方法是什么?

下面的方法看起来比简单地使用
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
已就位,因此您无需创建任何其他列表。

最佳方法取决于您具体执行的操作、此列表的来源以及实际数据的外观。为了简单起见,我删除了上下文。但我有一个文件名列表,我想按特定顺序读取。为了实现这一点,我想按照主要帖子中描述的方式对列表重新排序。