简体   繁体   中英

Declaring a Python list of expressions without evaluating each

I have a large number of arithmetic expressions that I store in a list. For example

exp_list = [exp1, exp2, ...,exp10000]

I also have indices of the few expressions I need to evaluate.

inds = [ind1,ind2,...,ind10]
exp_selected =  [exp_list[i] for i in inds ]

Is there a way to avoid having to evaluate all the expressions in exp_list?

Suppose you decide to store you expressions as lambdas (to avoid them being immediately evaluated) then you could selectively evaluate them with a simple list comprehension:

exp_list = [lambda: 1+2, lambda: 3+4, lambda: 5+6, lambda: 7+8]
inds = [1, 3]
print [exp() for i, exp in enumerate(exp_list) if i in inds]

Produces:

[7, 15]

If those expressions share some pattern and can be created 'mid-air' it would be better to use generator instead of just creating the list. Especially if you don't need to remember the results, but just check if any (or all) of them are true/false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM