I have a function which looks like that:
def roulette(self):
sum = 0
lst = []
for x in self.drinkList:
sum += x.fitness
lst.append(sum)
return lst
Can it be replaced with list comprehension expression or something more efficient than for loop?
PS: it apperars that if I do random.randrange(0), it raises an exception ValueError: empty range for randrange(). Is there a way to avoid it without using if test?
It’s actually possible to ‘peek’ at the list being built in a list comprehension. the outermost list has the name
_[1], which of course is not a valid python identifier, so it must be accessed in another way:But just because you can doesn’t mean you should; go with your
forloop, it looks like exactly what it does, and also doesn’t rely on an undocumented python feature.