作者:mobiledu2502872687 | 来源:互联网 | 2023-05-17 11:40
'''列表推导式[结果 fox循环 if语句]'''
lst = ["Python周末%s期" % i for i in range(1, 27) if i%2 == 0]
print(lst)
结果:
['Python周末2期', 'Python周末4期', 'Python周末6期', 'Python周末8期', 'Python周末10期', 'Python周末12期', 'Python周末14期', 'Python周末16期', 'Python周末18期', 'Python周末20期', 'Python周末22期', 'Python周末24期', 'Python周末26期']
'''列表生成式可以快速的创建一个列表'''
lst = [i*i for i in range(10)]
print(lst)
lst2 = [i if i <5 else i*i for i in range(10)]
print(lst2)
lst3 = [i*i for i in range(10) if i >= 5]
print(lst3)
lst4 = [i for i in ["apple", "orange", "banana", "pear"] if i.endswith("e")]
print(lst4)
'''使用列表推导式得到[1, 4, 9, 16, 25, 36]'''
print([i*i for i in range(1, 7)])
'''在[3,6,9]的基础上推到出[[1,2,3], [4,5,6],[7,8,9]]'''
print([[i-2, i-1, i] for i in [3, 6, 9]])
返回结果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 2, 3, 4, 25, 36, 49, 64, 81]
[25, 36, 49, 64, 81]
['apple', 'orange']
[1, 4, 9, 16, 25, 36]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
'''字典推导式{key:value fox循环 if语句}'''
lst = ["apple", "orange", "banana"]
dic = {k:v for k,v in enumerate(lst)}
print(dic)
返回结果:
{0: 'apple', 1: 'orange', 2: 'banana'}
'''集合推导式{key for循环 if语句}''' lst = [3, 5, 1, 5, 2, 1, 7] s = {i for i in lst} print(s)
返回结果:
{1, 2, 3, 5, 7}