![]() |
loop through list with do something - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: loop through list with do something (/thread-21640.html) |
loop through list with do something - 3Pinter - Oct-08-2019 I have to do something with all combinations in a list. Initial thought itertools.combinations(mylist, 2) But I have to something with the values of mylist and computing them over and over seems not logical. def myfunct(a) #do something with a #return something mylist = [1,2,3,4,5] for index, item in enumerate(mylist): val = myfunct(item) for i in mylist[index+1:]: # do something with 'val' and with iso in my example I only have to calculate 'val' once for each loop my thought is doing this with itertools I have to calculate val for each item everytime. Brainfart or could I do this better? RE: loop through list with do something - Gribouillis - Oct-08-2019 If the items in mylist are hashable, you could use functools.lru_cache from functools import lru_cache import itertools as itt def myfunct(a): #do something with a #return something print('myfunct({})'.format(a)) myf = lru_cache()(myfunct) mylist = [1,2,3,4,5] for x, y in itt.combinations(mylist, 2): val = myf(x) print(x, y) myf.cache_clear()
|