Bottom Page

• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 loop through list with do something 3Pinter Silly Frenchman Posts: 44 Threads: 16 Joined: Jun 2018 Reputation: 0 Likes received: 1 #1 Oct-08-2019, 11:21 AM (This post was last modified: Oct-08-2019, 11:21 AM by 3Pinter. Edited 2 times in total.) 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 i ```so 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? Gribouillis Posts: 2,051 Threads: 18 Joined: Jan 2018 Reputation: 184 Likes received: 489 #2 Oct-08-2019, 03:47 PM (This post was last modified: Oct-08-2019, 03:47 PM by Gribouillis. Edited 1 time in total.) 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() `````````Output: myfunct(1) 1 2 1 3 1 4 1 5 myfunct(2) 2 3 2 4 2 5 myfunct(3) 3 4 3 5 myfunct(4) 4 5 `````` « Next Oldest | Next Newest »

Top Page

 Possibly Related Threads... Thread Author Replies Views Last Post loop through list or double loop 3Pinter 4 640 Dec-05-2018, 06:17 AM Last Post: 3Pinter Write a for loop on list of lists without changing the shape of the main list Antonio 3 823 Jun-19-2018, 02:16 AM Last Post: ichabod801 For looping over a list, editing the list from inside the loop? Krookroo 3 1,441 Sep-04-2017, 05:08 PM Last Post: Krookroo How to change from printFacts ( ) to return a list & Loop over list when writing CSV Ivan1 14 2,821 Aug-30-2017, 12:14 PM Last Post: metulburr

Forum Jump:

Users browsing this thread: 1 Guest(s)