Reputation: 59
I have the following code:
fileTypes = ["photo", "audio"]
arg = {"photo": "123"}
is_file = True if [True for f in fileTypes if f in arg.keys()] else False
The is_file
output is True
, if "photo" or "audio" is one of the keys of arg
.
I want is_file
to return False
or one of file type, if it is set in arg
. One of the file types can be in the arg dict.
Also, I think this is not optimized. I'd like a better alternative.
Upvotes: 2
Views: 54
Reputation: 7100
What about any()
?
from timeit import timeit
def list_comprehension_method():
fileTypes = ["photo", "audio"]
arg = {"photo": "123"}
return True if [True for f in fileTypes if f in arg.keys()] else False
def any_method():
fileTypes = ["photo", "audio"]
arg = {"photo": "123"}
return any(f in arg.keys() for f in fileTypes)
number = 1000
print('any_method: ', timeit('f()', 'from __main__ import any_method as f', number=number))
print('list_comprehension_method: ', timeit('f()', 'from __main__ import list_comprehension_method as f', number=number))
Python 2.7:
any_method: 0.001070976257324218
list_comprehension_method: 0.001577138900756836
Python 3.6:
any_method: 0.0013788840005872771
list_comprehension_method: 0.0015097739960765466
Upvotes: 2