python - most pythonic way to interate a finite but arbitrary number of time through list values -
i trying optimize outcome genetic algorithm-style.
i provide seed value input function, transformations , returns "goodness value". pick best seed values, , repeat process until i've got winner.
the challenge i've run want run finite number of trials each step (say, 100 max) , number of seed values changes run run. using loop through list of seed values won't work me.
here solution came deal list not being infinite iterator:
iterations = 100 rlist = list(d.keys()) lt in (itertools.repeat(rlist)): d = gatherseedvalues(directory) seed = random.choice(lt) goodness = goodnessgracious(seed) goodnessdict[seed] = goodness if len(goodnessdict) > iterations: break
is there more pythonic way of doing - both in terms of getting around iterator restriction , looping strategy?
also, using len(goodnessdict)
methodology appropriate or there more pythonic way break loop?
based on comment:
rlist arbitrarily long - if has length of ten, i'd want iterate through 10x (100 total attempts). if has length of 500, i'd want process first 100 items.
what you're looking itertools.cycle
, itertools.islice
:
for item in itertools.islice(itertools.cycle(rlist), iterations): # item rlist
this iterate iterations
times, taking item rlist
on each go, starting on @ start if reaches end of list.
here's example range
:
for x in itertools.islice(itertools.cycle(range(4)), 10): print(x)
this print:
0 1 2 3 0 1 2 3 0 1
Comments
Post a Comment