Python list comprehension and dictionary comprehension

List comprehension

>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]

Dictionary comprehension

The two values ​​separated by a colon are used as key and value

>>> squares = {i: " {} squared is {}".format(i, i**2) for i in range(10)}
>>> squares
{0: ' 0 squared is 0', 1: ' 1 squared is 1', 2: ' 2 squared is 4', 3: ' 3 squared is 9', 4: ' 4 squared is 16', 5: ' 5 squared is 25', 6: ' 6 squared is 36', 7: ' 7 squared is 49', 8: ' 8 squared is 64', 9: ' 9 squared is 81'}
Published 89 original articles · Like 83 · Visits 3488

Guess you like

Origin blog.csdn.net/devin_xin/article/details/105435614