【问题标题】:check if expression within list comprehension is empty string检查列表理解中的表达式是否为空字符串
【发布时间】:2021-05-06 16:12:57
【问题描述】:

我有这个列表理解:

[''.join(letter for letter in word if not letter.isdigit()) for word in words]

我要做的是为列表words 中的每个word 检查word 是否包含数字。如果单词有数字字符,它将从最终输出中排除。

例如,remove_numbers(['lion', 'tiger99', 'yes7', '9']) 给我:

['lion', 'tiger', 'yes', '']

但是,我还想在最终输出中排除空字符串。所以想要的输出是:

['lion', 'tiger', 'yes']

我尝试在列表理解中添加if not word。不幸的是,这不起作用。有人可以帮忙吗?

【问题讨论】:

  • [''.join(letter for letter in word if not letter.isdigit()) for word in words if not word.isnumeric()]
  • 你可以使用正则表达式``` import re [ word if not re.search('\d',word) for word in words] ```
  • if not word.isnumeric() 不是if not word
  • 如果你想删除数字,你可以使用这个代码[re.sub('\d', '', word) for word in words if not word.isnumeric()]

标签: python python-3.x list list-comprehension


【解决方案1】:

if not word 在您的示例中不起作用,因为最后一个 "word" 不是空字符串 '' 但它是 '9',您的 已处理输出 是空字符串,它被附加到您的输出数组中。

@aminrd 的建议应该这样做,这里我们检查输入的单词是否纯数字,但这不适用于小数。

示例代码

words = ['lion', 'tiger300', 'yes7', '9']
print([''.join(letter for letter in word if not letter.isdigit()) for word in words if not word.isnumeric()])

# or using regex
import re
print([re.sub('\d', '', word) for word in words if not word.isnumeric()])

输出

['lion', 'tiger', 'yes']

既然您想知道如何在列表理解中检查输出单词是否为空

代码

words = ['lion', 'tiger300', 'yes7', '9']
print([x for x in [''.join(letter for letter in word if not letter.isdigit()) for word in words] if x])

输出

['lion', 'tiger', 'yes']

但是这种方法效率低,应该首选第一种方法,因为它只创建一个列表,这会创建两个列表,而且第一种更容易阅读。

【讨论】:

  • 如何在这个列表理解中检查附加输出是否为空?
  • @jxpython 对输出数组执行列表理解
  • @jxpython 我已经编辑了答案,但是第一种方法应该更有效,为什么要这样做?
  • 是 [re.sub('[0-9]', '', word) for word in words if not word.isnumeric()] 更好/更快吗?
  • @jxpython 我不确定哪个更快,但是您必须为此方法导入额外的模块。你也可以使用这个正则表达式re.sub('\d', '', word)
猜你喜欢
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多