python可以通过像这样的短格式语法生成具有多子路径的路径吗?
vars=project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}
答案 0 :(得分:1)
不,没有这样的内置速记。一种合理的pythonic方式是:
vars = ["project" + path for path in (
["/DEBIAN"] +
["/usr" + path for path in (
['/bin'] +
['/usr' + path for path in [
"/applications",
"/icons",
"/share"]
]
)] +
['/computer']
)]
您可以定义一个功能以使其更容易。这是一个懒惰的生成器版本:
def expand(base, paths):
for path in paths:
if type(path) == str:
yield base + path
else:
for p in path:
yield base + p
vars = expand("project", [
"/debian",
expand("/usr", [
"/bin",
expand("/usr", [
"/applications",
"/icons",
"/share"
]),
"/computer"
])
])
答案 1 :(得分:1)
通常我会建议使用像
这样的东西def extend(base, *others):
[base + o for o in others] if others else [base]
然后再做
extend("project", "/debian", *extend("/usr", *(extend("/bin") + extend("/usr", "/applications", "/icons", "/share"))))
。但是,由于您更喜欢解析字符串,我尝试提供替代方法:
def commasplit(s):
start = 0
level = 0
for i, c in enumerate(s):
if c == '{':
level += 1
elif c == '}':
level -= 1
elif c == ',' and level == 0:
yield s[start:i]
start = i+1
yield s[start:]
def split(s):
import re
found = False
for m in re.finditer("(\{.*\})",s):
found = True
for p in commasplit(s[m.start() + 1:m.end() - 1]):
for i in split(p):
yield s[:m.start()] + i + s[m.end():]
if not found:
yield s
cs = "a,b,c,{d,e,f},g"
print list(commasplit(cs)) # -> seems to work
s = "project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}"
print s
for n, i in enumerate(split(s)): print n, i # -> as well.
答案 2 :(得分:0)
谢谢。
我尝试编写代码。
我总是使用[“0,1,2,3,4,5,6,7,8,9”.split(“,”),[“a,b,c,d,e”.split (“,”)]]而不是正式列表。
因为它更快 - 没有移位按,显然,并且比[“x”,“y”,“z”]更有意义。
所以,我希望有一些字符串方法可以像bash一样,在代码中,在python中,很快...
Python语法:project,[DEBIAN,usr,[bin,usr,[applications,icons,share / winpath]],computer]
Bash语法:project / {DEBIAN,usr / {bin,usr / {applications,icons,share}},computer}
import re
def genpaths (multils, root=""):
suc=[]
for l in multils:
if type(l) == type([]):
suc.extend(genpaths (l, root+multils[multils.index(l)-1]+"/"))
else:
suc.append( root+l)
return filter(None, suc)
def easylist (s):
s=eval("['''"+re.sub("(\]+)(''',''')?", "'''\\1,'''",re.sub("(''',''')?(\[+)","''',\\2'''",re.sub(",","''','''",s)))+"''']")
return s
def bashlist (s):
s=eval("['''"+re.sub("(\}+)(''',''')?", "'''\\1,'''",re.sub("(/)?(\{+)","''',\\2'''",re.sub(",","''','''",s))).replace("{","[").replace("}","]")+"''']")
return s
def pythonGenPath (s):
return genpaths(bashlist (s))
def bashGenPath (s):
return genpaths(bashlist (s))
#testing
print pythonGenPath ("project,[DEBIAN,usr,[bin,usr,[applications,icons,share/winpath]],computer]")
print bashGenPath ("project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}")
结果是:
['project', 'project/DEBIAN', 'project/usr', 'project/usr/bin', 'project/usr/usr', 'project/usr/usr/applications', 'project/usr/usr/icons', 'project/usr/usr/share', 'project/computer']