Listed data generation possible

Is it possible to populate a list with a list simply by using a while statement?

Matching lists with:

r =  [i for i in range(0,5)]

r = [0, 1, 2, 3, 4]

Can this be built after a while?

Prototype:

i=0
print [i+=1 while i<5]
+4
source share
3 answers

You cannot exactly do what you want in understanding the list, but since you want to generate some elements while they meet the condition, it is better to create a generator from what you want (which creates elements on demand) and then filter your generator with itertools.takewhile.

>>> from itertools import takewhile
>>> list(takewhile(lambda x:x<5,range(5))) #in python 2.X pass an Xrange  
[0, 1, 2, 3, 4]
+1
source

An alternative is to use yield. For more complex operations, it can be simpler and more convenient to maintain:

def generate_less_than(val):
    i = 0
    while i < val:
        yield i
        i += 1

r = list(generate_less_than(5))

, , , list. .

+1

You are already on the right track. This works great:

print [i for i in range(5)]

You may also like the one-time variable, underscore:

print [_ for _ in range(5)]

This works to understand lists and other contexts where the index is not used outside the iteration.

-1
source

Source: https://habr.com/ru/post/1612297/


All Articles