返回信息流下面这件事,即“在if语句的条件里赋值”,C,Java能干,Python怎么也做不到:
package cn.byr.nuanyangyang;
import java.util.regex.*;
public class RegexpTest {
public static void main(String[] args) {
Pattern var = Pattern.compile("\\$([a-zA-Z]+)");
Pattern number = Pattern.compile("(\\d+)");
Pattern op = Pattern.compile("([+*/%-])");
String[] tokens = { "$foo", "123", "+" };
for (String token : tokens) {
Matcher m;
if ((m = var.matcher(token)).find()) {
String v = m.group(1);
System.out.println("Variable: " + v);
} else if ((m = number.matcher(token)).find()) {
int n = Integer.parseInt(m.group(1));
System.out.println("Number: " + n);
} else if ((m = op.matcher(token)).find()) {
char o = m.group(1).charAt(0);
System.out.println("Op: " + o);
} else {
System.out.println("Unrecognised token: " + token);
}
}
}
}
Python能做的只是下面这样:
import re
var = re.compile(r'\$([a-zA-Z]+)')
number = re.compile(r'(\d+)')
op = re.compile(r'([+*/%-])')
tokens = ["$foo", "123", "+"]
for token in tokens:
m = var.match(token)
if m:
v = m.group(1)
print("Variable: {}".format(v))
continue
m = number.match(token)
if m:
n = int(m.group(1))
print("Number: {}".format(n))
continue
m = op.match(token)
if m:
o = m.group(1)
print("op: {}".format(o))
continue
print("Unrecognised token {}".format(token))
还有什么更好的方法吗?
这是一条镜像帖。来源:北邮人论坛 / python / #10511同步于 2015/12/20
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
稍微黑一下Python,有什么好解决方案吗?
nuanyangyang
2015/12/20镜像同步17 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
其实我知道Guido大大是想避免一类bug:
a = input()
if a = "exit": # 应该是两个等号==
print("bye")
if "exit" == a: # 正确,但很丑陋,而且没必要。
print("bye")
但当潘多拉关上魔盒的时候,“希望”也被关在里面。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
var = re.compile(r'\$([a-zA-Z]+)')
number = re.compile(r'(\d+)')
op = re.compile(r'([+*/%-])')
tokens = ["$foo", "123", "+"]
for token in tokens:
v = var.match(token).group(1) if var.match(token) else None
if v is not None:
print("Variable: {}".format(v))
continue
n = number.match(token).group(1) if number.match(token) else None
if n is not None:
print("Number: {}".format(n))
continue
o = op.match(token).group(1) if op.match(token) else None
if o is not None:
print("op: {}".format(o))
continue
print("Unrecognised token {}".format(token))
#python的设计就是要尽量避免一些confuse吧,在if里不能赋值
#python程序员写出pythonic的代码
#好比说:
while (line = readline(file)) {
...do something with line...
}
#其实在python里更好的实现是迭代器
for line in file:
... do something with line ...
#而不是强行转换为以下这种:
while True:
line = file.readline()
if not line:
break
... do something with line ...
【 在 nuanyangyang 的大作中提到: 】
: 下面这件事,即“在if语句的条件里赋值”,C,Java能干,Python怎么也做不到:
: [code=java]
: package cn.byr.nuanyangyang;
: ...................
我只想说这个 稍微黑 就跟黑C、Java不能省略 ; 一样,语法就是这么定义的,为何要对着干。而且我觉得也没什么不好,正如你所说的避免了某些可能的错误。同时,我也不觉得if里面写个赋值表达式就是有什么 希望 ,遇到很长的表达式,可读性反而变差了。实在没必要省那么点事
【 在 wanghaohebe 的大作中提到: 】
: 我只想说这个 稍微黑 就跟黑C、Java不能省略 ; 一样,语法就是这么定义的,为何要对着干。而且我觉得也没什么不好,正如你所说的避免了某些可能的错误。同时,我也不觉得if里面写个赋值表达式就是有什么 希望 ,遇到很长的表达式,可读性反而变差了。实在没必要省那么点事
其实,C/Java程序员这样写的时候,是想完成一种模式匹配模式。这种语法一般只有函数式语言才有。比如Scala的正则表达式可以配合match-case语法:
package cn.byr.nuanyangyang.regexp
import scala.util.matching.Regex
object RegexpJunk extends App {
val Variable = """\$([a-zA-Z]+)""".r
val Number = """(\d+)""".r
val Op = """([+*/%-])""".r
val tokens = Seq("$foo", "123", "+")
tokens foreach {
case Variable(v) => printf("Variable: %s\n", v)
case Number(n) => printf("Number: %d\n", n.toInt)
case Op(o) => printf("Op: %c\n", o(0))
case token => printf("Unrecognised token: %s\n", token)
}
}
或者自己写一个matcher,在匹配的同时取出匹配的值:
object RegexpJunkWithAdvancedMatchers extends App {
class AdvancedMatcher[T](regex: Regex, mapper: String => T) {
def unapply(cs: CharSequence): Option[T] = regex.unapplySeq(cs).map(s => mapper(s(0)))
}
val Variable = new AdvancedMatcher[String]("""\$([a-zA-Z]+)""".r, identity)
val Number = new AdvancedMatcher[Int]("""(\d+)""".r, _.toInt)
val Op = new AdvancedMatcher[Char]("""([+*/%-])""".r, _(0))
val tokens = Seq("$foo", "123", "+")
tokens foreach {
case Variable(v) => printf("Variable: %s\n", v)
case Number(n) => printf("Number: %d\n", n)
case Op(o) => printf("Op: %c\n", o)
case token => printf("Unrecognised token: %s\n", token)
}
}
所以要黑Python嘛,这么漂亮的语言竟然没有这么好的功能。
简单的字典就可以,不需要写switch.
我觉得不在if里面赋值更容易理解,可读性更好。
if (a=find() and a is not None):
应该又可以实现赋值又可以判断,但是,好累。。
赋值语句的判断为真,这个nuanyangyang大神肯定知道的啦。
【 在 nuanyangyang 的大作中提到: 】
:
: 其实,C/Java程序员这样写的时候,是想完成一种模式匹配模式。这种语法一般只有函数式语言才有。比如Scala的正则表达式可以配合match-case语法:
: [code=scala]
: ...................