How to Collect Results of Repeated Calculations in a List or Dictionary
This question arises when we need to store the values obtained from repeated calculations using a loop or function. There are three common approaches to this problem:
Using an Explicit Loop:
Create a list or dictionary before the loop and add each computed value to it:
ys = [] for x in [1, 3, 5]: ys.append(x + 1)
This method is straightforward and works well with both for loops and while loops.
Using a Comprehension or Generator Expression:
ys = [x + 1 for x in [1, 3, 5]]
ys = {x: x + 1 for x in [1, 3, 5]}
Using the map Function:
map applies a specified function to each element in an iterable (list, tuple, etc.):
def calc_y(x): return x + 1 xs = [1, 3, 5] ys = list(map(calc_y, xs))
map returns an iterator that can be converted to a list, set, or dictionary.
Additional Considerations:
The above is the detailed content of How Can I Efficiently Store Results from Repeated Calculations in Python?. For more information, please follow other related articles on the PHP Chinese website!