In [4]: squares = [x**2 for x in range(10)]

In [5]: squares
Out[5]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [6]: [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y]
Out[6]: [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

normal-->Array based list comprehension-->function

In [7]: xarr = np.array([1.1,1.2, 1.3, 1.4, 1.5])

In [8]: yarr = np.array([2.1,2.2,2.3,2.4,2.5])

In [9]: conds = np.array([True,False,True,True,False])

In [10]: new_list = list()

In [11]: for x,y,cond in zip(xarr,yarr,conds):
    ...:     if cond:
    ...:         new_list.append(x)
    ...:     else:
    ...:         new_list.append( y )
In [12]: new_list
Out[12]: [1.1, 2,2, 1.3, 1.4, 2.5]
In [13]: new_list = [(x if c else y) for x,y,c in zip(xarr,yarr,conds)]

In [14]: new_list
Out[14]: [1.1, 2.2, 1.3, 1.4, 2.5]
In [15]: np.where(conds,xarr,yarr)
Out[15]: array([ 1.1,  2.2,  1.3,  1.4,  2.5])

results matching ""

    No results matching ""