List Generator

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']
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容