Mighty-Taungoo 5.1.3.List Comprehensions

List comprehensionsဆိုတာဘာလဲ?
List Comprehensions ဆိုသည်မှာlistတွေကိုcreateလုပ်ပီးconditionsအမျိုးမျိုးဖြင့်စစ်နိုင်ပါသည်။

squares=[] # struct empty array

for x in range(10): #using 'for' loop and range(10) is meaned 0 to 9.
squares.append(x**2) # added the squares value of 0 to 9 in array
[0,1,4,9,16,25,36,49,64,81] # invokes the square values of 0 to 9

List comprehensions is a complete substitute for the lambda function as well as the functions map(),filter() and reduce().

for eg.
squares=list(map(lambda x: x**2, range(10))
combs=[] # struct empty array
for x in [1,2,3]: # assign x in array
for y in [3,1,4]: # assign y in array
if x != y: # x and y are not equal
combs.append((x, y)) # print the pair of x and y if x and y are not equal
[(1,3), (1,4) , (2,3) ,(2,1), (2,4), (3,1), (3,4)] # invokes output of 'combs' array

vec=[-4, -2, 0, 2, 4] # struct 'vec' array
[x * 2 for x in vec] # create a new list with the value double
[-8, -4, 0, 4, 8]
[abs(x) for x in vec] # this function change (-) to (+)

fa=[ ' aa',' bb', ' cc ' ,' dd '] # struct 'fa' array
[ab.strip() for ab in fa ]# strip() function print the original array, if this array does not contain space and then return the answer with space.
[ 'aa' , 'bb' , 'cc' , 'dd' ]

vec = [ [1,2,3] , [4,5,6] ] # struct 'vec' array
[ a for b in vec for a in b ] # this function mixed the index number of array to become a whole array
[1,2,3,4,5,6]

from math import pi # impkement fot math
[ str( round (pi , i) ) for i in range(1, 6) ] # rounde() method cuts the decimal point with given range( range (1, 6) include 1 to 5)
['3.1' , '3.14' , '3.142' ,'3.1416' , '3.14159' ] # cut the decimal point according range for output

[str(round(1.12345670, i )) for i in range(1,6) # do not import with math
['1.1' , '1.1' , '1.12' , '1.123', '1.1234' , '1.12345' ]
Sign In or Register to comment.