Python_基础_5
生活随笔
收集整理的這篇文章主要介紹了
Python_基础_5
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1公共操作
str1 = 'aa' str2 = 'bb'list1 = [1, 2] list2 = [10, 20]t1 = (1, 2) t2 = (10, 20)dict1 = {'name': 'zyy'} dict2 = {'age': 20}# + 合并 字符串、列表、元組 print(str1 + str2) # aabb print(list1 + list2) # [1, 2, 10, 20] print(t1 + t2) # (1, 2, 10, 20) # print(dict1 + dict2) # 報錯 str1 = 'a' list1 = ['hello'] t1 = ('world', ) # 8 復制 字符串、列表、元組 print(str1 * 5) # aaaaa print('-' * 10) # ---------- print(list1 * 5) # ['hello', 'hello', 'hello', 'hello', 'hello'] print(t1 * 5) # ('world', 'world', 'world', 'world', 'world') str1 = 'abcd' list1 = [10, 20, 30] t1 = (100, 200, 300, 400) dict1 = {'name': 'Tom', 'age': 10}# in not in print('a' in str1) # True print('e' not in str1) # True print(10 in list1) # True print(100 not in list1) # True print(100 in t1) # True print(10 not in t1) # True print('name' in dict1) # True print('name' in dict1.keys()) # True print('name' in dict1.values()) # False str1 = 'abcd' list1 = [10, 20, 30] t1 = (100, 200, 300, 400) dict1 = {'name': 'Tom', 'age': 10}# len print(len(str1)) # 4 print(len(list1)) # 3 print(len(t1)) # 4 print(len(dict1)) # 2# del/del()# max min print(max(str1)) print(max(list1)) print(min(str1)) print(min(list1))# range(start,end,step) 可參考切片 for i in range(1, 10, 1):print(i, end=' ') else:print() # 1 2 3 4 5 6 7 8 9 for i in range(1, 10, 2):print(i, end=' ') else:print() # 1 3 5 7 9 for i in range(10):print(i, end=' ') else:print() # 0 1 2 3 4 5 6 7 8 9# enumerate() 函數用于一個可便利的數據對象(如列表、元組或字符串) # 組合為一個索引序列,同時列出數據和數據下標,一邊用在for循環當中 # enumerate(可遍歷對象,start = 0) start指的是起始值,默認為0list1 = ['a', 'b', 'c', 'd']for i in enumerate(list1):print(i, end=' ') else:print()for index, char in enumerate(list1, start=1):print(f'下標{index},對應的字符是{char}', end=' ') else:print() # 容器類型轉換 list1 = [10, 20, 30, 40, 30] s1 = {100, 200, 300} t1 = {'a', 'b', 'c', 'd', 'e'} print(tuple(list1)) # (10, 20, 30, 40) print(tuple(s1)) # (200, 100, 300)print(list(s1)) # [200, 100, 300] print(list(t1)) # ['b', 'c', 'd', 'a', 'e']print(list1) # [10, 20, 30, 40, 30] print(set(list1)) # {40, 10, 20, 30}2推導式
列表、字典、集合有推導式
2.1列表推導式
作用:用一個表達式創建一個有規律的列表或控制一個有規律列表
列表推導式又叫列表生式
2.2字典推導式
字典推導式作用:快速合并列表為字典或提取字典中目標數據
# 1 創建一個字典:字典key是1-5數字,value是這個數字的2次方 dict1 = {i: i**2 for i in range(1, 6)} print(dict1)# 2 將兩個列表合并為一個字典 list1 = ['name', 'age', 'sex'] list2 = ['Tom', 20, 'man']dict2 = {list1[i]: list2[i] for i in range(len(list1))} print(dict2) # 總結: # 如果兩個列表的個數相同,len統計任何一個列表的長度都可以 # 顆兩個列表數據個數不同,len統計個數多的會報錯,統計少的不會報錯 # 提取字典中目標數據 counts = {'MBP': 268, 'HP': 125, 'DELL': 200, 'Lenovo': 323, 'HuaWei': 1} # 需求:提取上述電腦數量大于等于200的字典數據 count1 = {key: value for key, value in counts.items() if value >= 200} print(count1) # {'MBP': 268, 'DELL': 200, 'Lenovo': 323}2.3集合推導式
# 需求:創建一個集合,數據為下方列表的2次方 # list1 = [1, 1, 2] list1 = [1, 1, 2] set1 = {i**2 for i in list1} print(set1)總結
以上是生活随笔為你收集整理的Python_基础_5的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python_基础_4
- 下一篇: Python_基础_6