Python從入門到精通

圖片.png

列表(list)

列表非常適合用于存儲在程序運行期間可能變化的數(shù)據(jù)集。

  1. 基礎(chǔ)操作:
    list = [ ]
    append('hello')
    insert(0,'hello')
    del list[0]
    list.pop() //pop出最后一個元素
    list.remove('hello')
    list.sort() //永久性排序
    list.sorted() //臨時性排序
    list.reserve()
    len(list)
    IndexError: list index out of range //下標越界
  2. 進階操作:
    遍歷 for i in list: //冒號別忘
    numbers = list(range(1,6)) even_numbers = list(range(2,11,2)) //用range函數(shù)創(chuàng)建列表
    min(list) max(list) sum(list)
    列表解析:squares = [value**2 for value in range(1,11)] //更快捷的創(chuàng)建列表
    列表切片:list[1:4] list[-3:] //列表后三個元素
    列表復(fù)制:深拷貝:friend_foods = my_foods[:] 淺拷貝:firiend_foods = my_foods

元組

Python將不能修改的值稱為不可變的,而不可變的列表被稱為元組。
相比于列表,元組是更簡單的數(shù)據(jù)結(jié)構(gòu)。如果需要存儲的一組值在程序的整個生命周期內(nèi)都
不變,可使用元組。

  1. 基礎(chǔ)操作:
    tuple = (200,50)
    tuple[0]
    遍歷:for i in tuple:
    修改元組可以重新賦值:tuple = (400,20)

小知識:

  1. 編寫Python改進提案(Python Enhancement Proposal,PEP),比較普遍的是PEP8,可以認為是行業(yè)規(guī)范

IF語句

  1. === != 的區(qū)別,python區(qū)分大小寫
  2. and or 連接兩個條件,建議各個條件用()分割
  3. 檢查特定值是否再列表中 if 'hello' in list: if 'hello' not in list:
  4. 布爾True False
  5. if-elif-else結(jié)構(gòu):else可以省略
if age < 4:
  print("Your admission cost is $0.")
elif age < 18:
  print("Your admission cost is $5.")
else:
  print("Your admission cost is $10.")

字典

  1. 創(chuàng)建使用:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
  1. 添加鍵值對:
    鍵—值對的排列順序與添加順序不同。 Python不關(guān)心鍵—值對的添加順序,
    而只關(guān)心鍵和值之間的關(guān)聯(lián)關(guān)系。
alien_0['x_position'] = 0
  1. 修改字典里的值:
alien_0['color'] = 'yellow'
  1. 刪除:
 del alien_0['points']
  1. 遍歷:
    for k, v in user_0.items(): 遍歷所有
    for name in favorite_languages.keys(): 遍歷所有的key
    for name in sorted(favorite_languages.keys()):按順序遍歷所有的鍵
    for language in favorite_languages.values():遍歷所有值
    for language in set(favorite_languages.values()):遍歷所有值,除重復(fù)
  2. 嵌套:列表,字典的包含與被包含:
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}

用戶輸入和while循環(huán)

  1. 用戶輸入:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

2.求模運算:%

函數(shù)

  1. 實參與形參:
    def greet_user(username) def greet_user("hello")
  2. 形參默認值:
    describe_pet(pet_name='willie')
  3. 讓實參變成可選:
def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整潔的姓名"""
  if middle_name:
    full_name = first_name + ' ' + middle_name + ' ' + last_name
  else:
    full_name = first_name + ' ' + last_name
musician = get_formatted_name('jimi', 'hendrix')
  1. 在函數(shù)中修改列表,在函數(shù)中對這個列表所做的任何修改都是永久性的,這讓你能夠高效地處理大量的數(shù)據(jù)。
  2. 傳遞任意數(shù)量實參:
def make_pizza(*toppings):
"""打印顧客點的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

其中toppings是一個元組

  1. 結(jié)合使用位置實參和任意數(shù)量實參:
def make_pizza(size, *toppings):
"""概述要制作的比薩"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
  1. 使用任意數(shù)量的關(guān)鍵字實參:
def build_profile(first, last, **user_info):
"""創(chuàng)建一個字典,其中包含我們知道的有關(guān)用戶的一切"""
  profile = {}
  profile['first_name'] = first
  profile['last_name'] = last
  for key, value in user_info.items():
    profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)

形參**user_info中的兩個星號讓Python創(chuàng)建一個名為user_info的空字典,并將收到的所有名稱—值對都封裝到這個字典中。在這個函數(shù)中,可以像訪問其他字典那樣訪問user_info中的名稱—值對。

  1. 將函數(shù)存儲在模塊中,as重命名
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容