相关疑难解决方法(0)

我们可以在条件下进行任务吗?

是否可以在条件下进行分配?

对于前者

if (a=some_func()):
    # Use a
Run Code Online (Sandbox Code Playgroud)

python

76
推荐指数
7
解决办法
6万
查看次数

你如何将这个正则表达式的习惯用法从Perl翻译成Python?

大约一年前我从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中重现这种模式?我已经看过使用匿名函数调度表,但对于少数正则表达式来说,这些对我来说似乎有点笨拙......

python regex perl

45
推荐指数
6
解决办法
8779
查看次数

如何在Python中的while(表达式)循环内进行变量赋值?

我有变量赋值,以便返回指定的值并直接在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中有没有办法做到这一点?

python syntax expression while-loop

15
推荐指数
3
解决办法
9021
查看次数

在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不允许这种语法.在这种情况下,我该怎么做才能避免深度缩进?

python conditional indentation

3
推荐指数
1
解决办法
131
查看次数

在 while 比较表达式中赋值

嗨,我想知道是否可以在代码的 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

1
推荐指数
1
解决办法
5689
查看次数