大约一年前我从Perl切换到Python,并没有回头.我发现只有一个习惯用法在Perl中比在Python中更容易做到:
if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
Run Code Online (Sandbox Code Playgroud)
相应的Python代码并不那么优雅,因为if语句不断嵌套:
m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
Run Code Online (Sandbox Code Playgroud)
有没有人有一种优雅的方式在Python中重现这种模式?我已经看过使用匿名函数调度表,但对于少数正则表达式来说,这些对我来说似乎有点笨拙......
我有变量赋值,以便返回指定的值并直接在while循环中将其与空字符串进行比较.
以下是我在PHP中的表现:
while((name = raw_input("Name: ")) != ''):
names.append(name)
Run Code Online (Sandbox Code Playgroud)
我正在尝试做的与功能相同:
names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
Run Code Online (Sandbox Code Playgroud)
在Python中有没有办法做到这一点?
当我编写如下代码时,我会深陷缩进
match = re.search(some_regex_1, s)
if match:
# do something with match data
else:
match = re.search(some_regex_2, s)
if match:
# do something with match data
else:
match = re.search(soem_regex_3, s)
if match:
# do something with match data
else:
# ...
# and so on
Run Code Online (Sandbox Code Playgroud)
我试着重写为:
if match = re.search(some_regex_1, s):
# ...
elif match = re.search(some_regex_2, s):
# ...
elif ....
# ...
...
Run Code Online (Sandbox Code Playgroud)
但Python不允许这种语法.在这种情况下,我该怎么做才能避免深度缩进?
嗨,我想知道是否可以在代码的 while 比较部分中分配一个值。
这是当前的代码示例
startIndex = find(target, key, startIndex)
while( startIndex != -1):
matchesFound += 1
startIndex = find(target, key, startIndex + 1)
return matchesFound
Run Code Online (Sandbox Code Playgroud)
我想要做的是将 startIndex = find(target, key, startIndex) 移动到 while 比较表达式中,因此它看起来像这样
while( (startIndex = find(target, key, startIndex)) != -1):
matchesFound += 1
startIndex + 1
return matchesFound
Run Code Online (Sandbox Code Playgroud)
如果没有,更好的重构是什么?
谢谢
编辑 在尝试著名的 6.001 模块之前,我正在学习 MIT Open 课件 6.00
python ×5
conditional ×1
expression ×1
indentation ×1
perl ×1
regex ×1
syntax ×1
while-loop ×1