Use of Python list derivation

  • 2020-04-02 13:11:51
  • OfStack

1. List derivation writing form:

[list of expression for variable in]       or   [expression for variable in list if condition]

2. Illustration:


#!/usr/bin/python
# -*- coding: utf-8 -*-
li = [1,2,3,4,5,6,7,8,9]
print [x**2 for x in li]
print [x**2 for x in li if x>5]
print dict([(x,x*10) for x in li])

print  [ (x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8 ]
vec=[2,4,6]
vec2=[4,3,-9]
sq = [vec[i]+vec2[i] for i in range(len(vec))]
print sq
print [x*y for x in [1,2,3] for y in  [1,2,3]]
testList = [1,2,3,4]
def mul2(x):
    return x*2
print [mul2(i) for i in testList]

Results:

[1, 4, 9, 16, 25, 36, 49, 64, 81]
[36, 49, 64, 81]
{1:10, 2:20, 3:30, 4:40, 5:50, 6:60, 7, 70, 8, 80, 9:90}
[(5, 9), (7, 9), (9, 9)]
[6, 7, 3]
[1, 2, 3, 2, 4, 6, 3, 6, 9]
[2, 4, 6, 8]

3. Conclusion:
I think it's a for statement that deals with the variables in the expression, and if you're going to add a condition, add an if condition.


Related articles: