str1 = '123' str2 = '2' list1 = [1, '2'] list2 = [3, 4] tuple1 = (1, 2, '3') tuple2 = (4, 5, 6) dict1 = {'name': 'wang','age': 18} dict2 = {'weight': 80, 'name': 'xiao'} set1 = {1, 2, 3} set2 = {3, 4, 5} print(str1+str2) print(list1+list2) print(tuple2+tuple1) print(str2*10) print('str'*5) print(list1*3) print(tuple2*3) print('1' in str1) print(4 not in list2) print(4 in tuple2) print('name' in dict1) print('wang' in dict1) #字典里面只能查键名
dict1 = {1: 2, 'abc': 3}
print(max(dict1)) #返回报错
s = 'aasssfff' l = ['h', 'i', 'j', 'k', 'l'] d = {'a': 1, 'b': 2} z = ('m', 'n', 'o', 'p', 'q') t = {'a', 'b', 'd', 'e', 'f'} for i in enumerate(s): print(i) for i in enumerate(l): print(i) for i in enumerate(d): print(i) for i in enumerate(d): print(i) for i in enumerate(z): print(i) for i in enumerate(t): print(i) for index, val in enumerate(t): #同时输出下标和值 print(index, val)
需求:创建一个存放1-10的数据的列表
list1 = [] i = 0 while i < 10: list1.append(i) i += 1 print(list1)
list1 = [] for i in range(10): list1.append(i) print(list1)
list1 = [i for i in range(10)] print(list1)
需求创建一个0-10的并且只包含偶数的列表
list1 = [i for i in range(0, 10, 2)] print(list1)
list2 = [] for i in range(10): if i % 2 == 0: list2.append(i) print(list2)
list3 = [i for i in range(10) if i % 2 == 0] print(list3)
如果要求创建的一个列表如下:
[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list1 = [] for i in range(1, 3): for j in range(3): # 列表里面追加元组: 循环前准备一个空列表,然后这里追加元组数据到列表 list1.append((i, j)) print(list1)
list2 = [(i, j) for i in range(1, 3) for j in range(3)] print(list2)
作用:常常用来把列表合并成为字典或提取字典中的目标数据。
{1: 1, 2: 4, 3: 9, 4: 16}
字典推导式实现:
dict1 = {i: i**2 for i in range(1, 5)} print(dict1)
【注:】python中可以使用 **
运算符轻松完成一个数的n次方运算。
print(2**3) #2的3次方,结果为8
['name', 'age', 'gender', 'id'] ['Tom', 20, 'man']
字典推导式实现:
list1 = ['name', 'age', 'gender', 'id'] list2 = ['Tom', 20, 'man'] dict1 = {list1[i]: list2[i] for i in range(len(list2))} print(dict1) #{'name': 'Tom', 'age': 20, 'gender': 'man'}
数据:
{'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
需求:提取电脑台数大于等于200的字典数据
dict1 = {key: value for key, value in counts.items() if value >= 200} print(dict1) #{'MBP': 268, 'DELL': 201}
用的不多,简单过一下。
list1 = [1, 1, 2] set1 = {i ** 2 for i in list1} print(set1) #{1, 4}