不完全由数字组成的单词的 Python 列表理解

标签 python list list-comprehension

在高层次上,我想要完成的是:

given a list of words, return all the words that do not consist solely of digits

我首先想到的是:

import string
result = []
for word in words:
    for each_char in word:
        if each_char not in string.digit:
            result.append(word)
            break
return result

这很好用。为了更 Pythonic,我想 - 列出推导式,对吧?所以:

return [word for word in words for char in word if not char in string.digits]

不幸的是,这会将 word 的副本添加到每个非数字字符的结果中。所以对于 f(['foo']),我最终得到了 ['foo', 'foo', 'foo']

是否有一种聪明的方法来完成我想做的事情?我目前的解决方案是只编写一个 is_all_digits 函数,然后说 [word for word in words if not is_all_digits(word)]。我的一般理解是列表理解允许这种操作是声明性的,而辅助函数对我来说是充分的声明性的;只是好奇是否有一些聪明的方法可以使它成为一个复合语句。

谢谢!

最佳答案

为什么不检查整个字符串的 isdigit():

>>> words = ['foo', '123', 'foo123']
>>> [word for word in words if not word.isdigit()]
['foo', 'foo123']

或者,将逻辑转换为其他方式并使用 any():

>>> [word for word in words if any(not char.isdigit() for char in word)]
['foo', 'foo123']

any() 将在单词的第一个非数字字符处停止并返回 True

关于不完全由数字组成的单词的 Python 列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051294/

相关文章:

python - 根据来自另一个列表的 True/False 过滤列表中的元素

python - 使用python在linux中访问文件的时间

python - 在 Python 的巨大列表中搜索(数字)字符串的匹配项

python - numpy 数组列表格式

python - Flask 使用 add_url_rule 路由到方法

python - 在 Python 中从数据源创建多个文件

r - 在 R 中向列表中添加元素的最快方法

字符串解析的python列表

python - 如何将 2 列常量添加到指定位置的列表中?

Elixir [42] 打印为 '*'