【问题标题】:How does list comprehension work in this code block? [duplicate]列表理解如何在此代码块中工作? [复制]
【发布时间】:2019-09-27 03:41:50
【问题描述】:

在下面的代码块中,我知道 s 是字符串。 re.split() 将生成一个拆分结果列表,列表推导将遍历创建的每个结果。

我不明白“如果我”在这里如何工作。

这来自以下 stackoverflow 线程:https://stackoverflow.com/a/28290501/11292262

s = '125km'
>>> [i for i in re.split(r'([A-Za-z]+)', s) if i]
['125', 'km']
>>> [i for i in re.split(r'(\d+)', s) if i]
['125', 'km']

【问题讨论】:

  • 只删除re.split产生的空项目
  • if i 将确保列表中不会保留任何空匹配项。如果i 为空,则基本上if i 返回false

标签: python regex list split list-comprehension


【解决方案1】:

空字符串计算为False。注意当我们取出if 时会发生什么:

import re
s = '125km'

print(re.split(r'([A-Za-z]+)', s))
print(re.split(r'(\d+)', s))

输出:

['125', 'km', '']
['', '125', 'km']

if 用于根据该问题删除不需要的空字符串。请注意,两个表达式中的捕获组都需要确保the part of the string split on (value or unit) is also returned

【讨论】:

  • 啊,好吧,太好了,这很有道理!我假设你必须写如果 i = '' 或其他东西。 “如果变量”是作为函数嵌入到 python 中的东西吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2016-11-16
相关资源
最近更新 更多