List Generator

2018-09-10  本文已影响0人  bin_guo

Generate list by simple expression

Like slicing, the first digit is the index of the first element you want to start from, the second digit is the next one of the last element you picked, we use range(1,10) = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Python provides the possibility to simplify the code, easily put expression to the index of [], like [expression ranges condition]
example

//Code==========
L = [x * x for x in range(1, 11)]
print (L)
//Result==========
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Generate list by complex expression

Even you can pass a function to be a expression
example

//Code==========
d = { 'Bin': 95, 'Lisa': 85, 'Bart': 59 }
def passed_filter(name, score):
    if(score >= 60):
        return name, score
  else:
        return None
passed = [passed_filter(name, score) for name, score in d.items()]
print (passed)
//Result==========
[('Bin', 95), ('Lisa', 85), None]

Generate list with condition

Like where in SQL
example

//Code==========
L = [x * x for x in range(1, 11)]
print (L)
L2 = [x * x for x in range(1, 11) if x % 2 == 0]
print (L2)
//Result==========
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[4, 16, 36, 64, 100]

Generate list with nested for loop

It is NESTED for loop of outter for loop, not separate for loops
example

//Code==========
L = [m + n for m in 'ABC' for n in '123']
print (L)
L2 = []
for m in 'ABC':
    for n in '123':
        L2.append(m + n)
print (L2)
//Result==========
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
上一篇下一篇

猜你喜欢

热点阅读