赞
踩
- # 1. 准备⼀个空列表
- list1 = []
- # 2. 书写循环,依次追加数字到空列表list1中
- i = 0
- while i < 10:
- list1.append(i)
- i += 1
- print(list1)
示例代码:【for循环实现】
- list1 = []
- for i in range(10):
- list1.append(i)
- print(list1)
运行结果:
示例代码:【列表推导式实现】
- list1 = [i for i in range(10)]
- print(list1)
运行结果:
- list1 = [i for i in range(0, 10, 2)]
- print(list1)
- list1 = [i for i in range(10) if i % 2 == 0]
- print(list1)
运行结果:
[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
- # 【先执行前面的for循环】
- lst = [(i, j) for i in range(7, 9) for j in range(3)]
- print(lst)
运行结果:
快速合并列表为字典或提取字典中⽬标数据。
- list1 = ['name', 'age', 'gender']
- list2 = ['Tom', 20, 'man']
- dict1 = {i: i ** 2 for i in range(1, 5)}
- print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16}
运行结果:
- list1 = ['name', 'age', 'gender']
- list2 = ['Tom', 20, 'man']
- dict1 = {list1[i]: list2[i] for i in range(len(list1))}
- print(dict1)
运行结果:
- counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
- # 需求:提取上述电脑数量⼤于等于200的字典数据
- count1 = {key: value for key, value in counts.items() if value >= 200}
- print(count1) # {'MBP': 268, 'DELL': 201}
运行结果:
示例代码:
- # 数据类型一
- dic1 = {'aa': {'AA': 4}, 'bb': {'BB': 6}}
- dic2 = {'aa': {'CC': 9}, 'bb': {'DD': 0}}
- print(set(dic1) | set(dic2))
-
- dic = {key: {**dic1.get(key), **dic2.get(key)} for key in set(dic1) | set(dic2)}
- print(dic)
-
- # 数据类型二
- dic1 = {'aa': 4, 'bb': 6}
- dic2 = {'aa': 9, 'bb': 0}
- print(set(dic1) | set(dic2))
-
- dic = {key: {dic1.get(key), dic2.get(key)} for key in set(dic1) | set(dic2)}
- print(dic)
运行结果:
示例代码:
- # 数据类型一
- dic1 = {'cc': {'AA': 4}, 'ee': {'BB': 6}}
- dic2 = {'ff': {'CC': 9}, 'ee': {'DD': 0}}
- print(set(dic1) | set(dic2))
-
- # 下面这种情况get里面要加默认值,否则会报错
- dic = {key: {**dic1.get(key, {}), **dic2.get(key, {})} for key in set(dic1) | set(dic2)}
- print(dic)
-
- # 数据类型二
- dic1 = {'cc': 4, 'ee': 6}
- dic2 = {'ff': 9, 'ee': 0}
- print(set(dic1) | set(dic2))
-
- # 下面这种情况get里面要加默认值,否则会报错
- dic = {key: {dic1.get(key), dic2.get(key)} for key in set(dic1) | set(dic2)}
- print(dic)
运行结果:
示例代码:
- # 字典推导式
-
- dic = {"name": "dgw", "age": 25, "sex": "男"}
- print(dic)
-
- # 交换字典key和value的值
- dic2 = {value: key for key, value in dic.items()}
- print(dic2)
-
- # {'name': 'dgw', 'age': 25, 'sex': '男'}
- # {'dgw': 'name', 25: 'age', '男': 'sex'}
运行结果:
list1 = [1, 1, 2]
- list1 = [1, 1, 2]
- set1 = {i ** 2 for i in list1}
- print(set1) # {1, 4}
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。