在 if 语句中重写赋值的 pythonic 方法

标签 python syntax if-statement

是否有我会在 C++ 中执行此操作的 pythonic 首选方法:


for s in str:
    if r = regex.match(s):
        print r.groups()

我真的很喜欢这种语法,我觉得它比到处都是临时变量要干净得多。唯一不太复杂的其他方法是


for s in str:
    r = regex.match(s)
    if r:
        print r.groups()

我想我是在提示一个相当迂腐的问题。我只是想念以前的语法。

最佳答案

怎么样

for r in [regex.match(s) for s in str]:
    if r:
        print r.groups()

或者更实用一些

for r in filter(None, map(regex.match, str)):
    print r.groups()

关于在 if 语句中重写赋值的 pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3744382/

相关文章:

flutter - 根据索引/变量更改小部件的颜色

python - 尝试使用 python-mysql-connector 建立与 Mysql 服务器的 SSL 连接时访问被拒绝

python - 使用python解析和匹配html的奇怪结构

perl - 无法识别语法错误

syntax - 为什么在模式匹配中使用 `ref` 而不是星号?

php - MySQL 查询 - WHERE 和 IF?

javascript - if/else 语句仅记录 if,不记录 else

python - APScheduler 作业未按计划启动

python - windows 7 32位系统pytorch安装

matlab - ~= 在 MATLAB 中是什么意思?