推导式的学习
# 依次加入列表里 # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list1 = [] i = 0 while i < 10: list1.append(i) i += 1 print(list1) list2 = [] for i in range(10): list2.append(i) print(list2) list3 = [i for i in range(10)] print(list3)
# 要求是键是1-5 值是它的平方 # {1: 1, 2: 4, 3: 9, 4: 16} dict1 = {} for i in range(1, 5): dict1[i] = i ** 2 print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16} dict2 = {i: i ** 2 for i in range(1, 5)} print(dict2) # {'1': '4', '2': '5', '3': '6'} name1 = ["1", "2", "3"] name2 = ["4", "5", "6"] dict3 = {name1[i]: name2[i] for i in range(len(name1))} print(dict3) # {'1': '4', '2': '5', '3': '6'} name3 = ["1", "2", "3"] name4 = ["4", "5", "6"] dict4 = {} for i in range(len(name3)): dict4[name3[i]] = name4[i] print(dict4)
# [0, 2, 4, 6, 8] # [0, 2, 4, 6, 8] # [1, 3, 5, 7, 9] list1 = [i for i in range(0, 10, 2)] print(list1) list2 = [i for i in range(10) if i % 2 == 0] print(list2) list3 = [i for i in range(10) if i % 2 == 1] print(list3)
list1 = [1, 2, 3] set1 = set() for i in list1: set1.add(i ** 2) print(set1) # {1, 4, 9} set2 = {i ** 2 for i in list1} print(set2) # {1, 4, 9}