Is this boolean test pythonic for limiting a list's members to a set of legal values?
I have a list of legal words:
legal = ['osama','bin','laden']
A function accepts a 开发者_JS百科list that must contain words in the legal list & returns true if every member of the list is a legal word.
def is_legal( list ):
return not any( [tok not in legal for tok in list ] )
It's easier to read if you use all()
instead of any()
:
legal = set(['osama','bin','laden'])
def is_legal(seq):
return all(tok in legal for tok in seq)
You don't want the square brackets (since they force creation of a list), and you don't want to shadow builtins, but yes.
def is_legal(seq):
return not any(tok not in legal for tok in seq)
all((token in LEGAL_TOKENS) for token in mySequence)
I prefer:
legal = {'osama','bin','laden'} # or set(['osama','bin','laden']) if not 2.7+
is_legal = legal.issuperset
精彩评论