You do not need to use a for loop. The loop is five times and a random value is obtained.
Result = [random. randint (1,100) for X in range (5)]
Result = [[random. randint (1,100) for X in range (5)] for Y in range (5)]
Refer:
List comprehension and generator expression in Python)
List parsing:
Syntax: [expr for iter_var in iterable] or [expr for iter_var in iterable if cond_expr]
Note:
First, iterate all the content in iterable. In each iteration, the corresponding content in iterable is put into iter_var, and then the content of iter_var is applied to the expression, finally, a list is generated using the calculated value of the expression.
Syntax 2: A judgment statement is added. Only the content that meets the conditions puts the corresponding content in iterable into iter_var, and then applies the content of the iter_var in the expression, finally, a list is generated using the calculated value of the expression.
Example:
>>> [I + 1 for I in range (10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [I + 1 for I in range (10) If I % 2]
[2, 4, 6, 8, 10]
Generator expression:
Syntax: (expr for iter_var in iterable) or (expr for iter_var in iterable if cond_expr)
Description: List Parsing is introduced in earlier Python versions (like version 2.0), while generator expressions are new content introduced in version 2.4, it is similar to the list parsing syntax, but the advantage of the generator expression is reflected in the processing of large data volumes, because it has better memory usage and higher efficiency, it does not create a list, but returns a generator. Of course, list parsing will not be abandoned.
Example:
>>> (I + 1 for I in range (10) If I % 2)
<Generator object <genexpr> at 0x011dc5d0>
>>> G = (I + 1 for I in range (10) If I % 2)
>>> L = []
>>> For J in G:
L. append (j)
>>> L
[2, 4, 6, 8, 10]
It can be seen from the above that, although the list parsing syntax is similar to the generator expression syntax, it is actually quite different.
Python is very powerful, elegant, efficient, concise, and interesting. I hope more people will come to know it.
Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but with parentheses instead of brackets.
These expressions are designed for situations where the generator is used right away by an enclosing function.
Generator expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions.
Refer:
Python tutorial
Http://home.ixpub.net/space.php? Uid = 16111523 & Do = Blog & id = 404460