mfr*_*kli 9 python list-comprehension list
在高层次上,我想要完成的是:
given a list of words, return all the words that do not consist solely of digits
Run Code Online (Sandbox Code Playgroud)
我第一次想到如何做到这一点是:
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
Run Code Online (Sandbox Code Playgroud)
这很好用.为了更加Pythonic,我想 - 列表理解,对吗?所以:
return [word for word in words for char in word if not char in string.digits]
Run Code Online (Sandbox Code Playgroud)
不幸的是,这会word为每个不是数字的字符添加结果副本.所以f(['foo']),我最终得到了['foo', 'foo', 'foo'].
有没有一种聪明的方法可以做我想做的事情?我目前的解决方案是编写一个is_all_digits函数,然后说[word for word in words if not is_all_digits(word)].我的一般理解是列表推导允许这种操作是声明性的,并且辅助函数对我来说是充分的声明; 只是好奇是否有一些聪明的方法使它成为一个复合语句.
谢谢!
ale*_*cxe 14
为什么不检查整个字符串isdigit():
>>> words = ['foo', '123', 'foo123']
>>> [word for word in words if not word.isdigit()]
['foo', 'foo123']
Run Code Online (Sandbox Code Playgroud)
或者,以其他方式转换逻辑并使用any():
>>> [word for word in words if any(not char.isdigit() for char in word)]
['foo', 'foo123']
Run Code Online (Sandbox Code Playgroud)
any()将停在一个单词的第一个非数字字符并返回True.