如何在python中从上到下遍历每条路径?

时间:2016-01-28 08:19:44

标签: python list maya

给出一个字符串

s='MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom'

在python 2.7中获取这样一个列表的最简单方法是什么?

['MayaWindow','MayaWindow|toolBar2','MayaWindow|toolBar2|MainShelfLayout','MayaWindow|toolBar2|MainShelfLayout|formLayout14','MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout','MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom']

如:

import re
for t in s.split('|'):
    print re.search(r'.*%s'%t,s).group()

但如果路径中的某些文件夹名称不唯一,则会中断,例如

s='MayaWindow|toolBar2|MainShelfLayout|formLayout14|formLayout14|Custom'

import re
for t in s.split('|'):
    print re.search(r'.*%s'%t,s).group()

MayaWindow
MayaWindow|toolBar2
MayaWindow|toolBar2|MainShelfLayout
MayaWindow|toolBar2|MainShelfLayout|formLayout14|formLayout14
MayaWindow|toolBar2|MainShelfLayout|formLayout14|formLayout14
MayaWindow|toolBar2|MainShelfLayout|formLayout14|formLayout14|Custom

3 个答案:

答案 0 :(得分:2)

来自Python 3.2的

itertools.accumulate允许我们避免使用索引

from itertools import accumulate
s = 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom'

new_list = list(accumulate(s.split('|'), lambda x,y: '|'.join((x,y))))

print(new_list)

产生

['MayaWindow', 'MayaWindow|toolBar2', 'MayaWindow|toolBar2|MainShelfLayout', 'MayaWindow|toolBar2|MainShelfLayout|formLayout14', 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout', 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom']

另一方面,在Python 2中,你可以沿着这条线做点什么

elements = iter(s.split('|'))
acc = next(elements)
new_list = [acc, ]
for el in elements:
    acc += '|'+el
    new_list.append(acc)

print(new_list)

答案 1 :(得分:2)

单行:

>>> [s.rsplit("|", i)[0] for i in range(s.count("|"), -1, -1)]
['MayaWindow',
 'MayaWindow|toolBar2',
 'MayaWindow|toolBar2|MainShelfLayout',
 'MayaWindow|toolBar2|MainShelfLayout|formLayout14',
 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout',
 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom']

答案 2 :(得分:1)

将其拆分到感兴趣的分隔符上,然后遍历每个切片大小:

s = 'MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom'
l = s.split('|')
new_list = [l[:idx] for idx in range(1, len(l)+1)]

结果:

>>> for item in new_list:
...     print(*item)
...
MayaWindow
MayaWindow toolBar2
MayaWindow toolBar2 MainShelfLayout
MayaWindow toolBar2 MainShelfLayout formLayout14
MayaWindow toolBar2 MainShelfLayout formLayout14 ShelfLayout
MayaWindow toolBar2 MainShelfLayout formLayout14 ShelfLayout Custom

或者如果你想要字符串而不是list s,join()它们会回到分隔符上:

new_list = ['|'.join(l[:idx]) for idx in range(1, len(l)+1)]

结果:

>>> for item in new_list:
...     print(item)
...
MayaWindow
MayaWindow|toolBar2
MayaWindow|toolBar2|MainShelfLayout
MayaWindow|toolBar2|MainShelfLayout|formLayout14
MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout
MayaWindow|toolBar2|MainShelfLayout|formLayout14|ShelfLayout|Custom