2015-08-15 106 views
-2

我有一个文件名列表,通过他们的“文件类型”,如现下令: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'] 

这些列表的长度可能是巨大的,所以我会假设效率是关键。什么是最好的方法来解决这个问题?

+0

_best_方式取决于你在做什么,这个列表来自哪里以及真实数据是什么样子。 – Cyphase

+0

为了简单起见,我删除了上下文。但我所拥有的是我想以特定顺序阅读的文件名列表。为了实现这一点,我想按照主文章中所述的方式对列表重新排序。 – Samuel

回答

1

下面看起来比它应该只使用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'] 
1

你只需要通过强制转换为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被就地所以你不需要建立任何其他列表。