04-python的列表操作

來源:互聯網
上載者:User

標籤:ict   操作   matrix   reverse   返回   多少   嵌套   --   pop   

python中列表的使用最多, 常用的方法有: 

append(value)extend(L)   添加指定列表的所有元素insert(index, value)    插入remove(value)pop(index)        不指定刪除最後一個,clear()         清空count(value)    統計有多少個sort()          排序reverse()       到序copy()          潛複製

其他的: 

1, 列表推導式

列表推到式, 從序列簡單的建立列表
將操作應用於序列的每個元素, 將其結果作為新的列表元素
需要用 [], 元組用()
每個列表推到是都在for之後建立一個運算式, 然後有0-多個 for或if子句, 返回結果
是一個根據運算式從背後的for和if上下文環境中產生的列表, 如果希望推到出一個元組, 必須用口號
# ×3 擷取一個新的列表vec = [2, 4, 6]new_vec = [3 * x for x in vec]print(new_vec)# 擷取一個mapdict = [(x, x**2) for x in vec]print(dict)# 對序列中元素租個調用fruits = [‘banana‘, ‘apple‘, ‘oragin‘]new_fruits = [fruit.upper() for fruit in fruits]print(new_fruits)# 使用ifif_vec = [3 * x for x in vec if x > 3]print(if_vec)# 2個列表混搭的vec2 = [4, 6, -1]lista = [x * y for x in vec for y in vec2]listb = [vec[i] * vec2[i] for i in range(len(vec))]print(lista)print(listb)

字典推導

# 字典 推導new_dict = {x + 10: x**2 + 10 for x in range(10)}print(new_dict)

 

2, 嵌套列表的轉換

比如, 我想把一個 3 * 4 的列錶轉換為 4 * 3 的列表

matrix = [    [1, 2, 3, 4],    [5, 6, 7, 8],    [9, 10, 11, 12]]new_matrix = [[row[i] for row in matrix] for i in range(4)]print(new_matrix)# 上面的相當於matrix_1 = []for i in range(4):    matrix_1.append([row[i] for row in matrix])print(matrix_1)# 擷取進一步改寫matrix_2 = []for i in range(4):    ineer = []    for row in matrix:        ineer.append(row[i])        print(row[i], end=‘, ‘)    print(‘---‘, row)print(matrix_2)for row in matrix:    print(row)

 

3, 使用enumerate進行遍曆
# 字典 推導new_dict = {x + 10: x**2 + 10 for x in range(10)}print(new_dict)# 字典的遍曆for k, v in new_dict.items():    print(k, v)# 返回索引的, dict返回keyfor i, v in enumerate(new_dict):    print(i, v)# 遍曆2個貨更多的序列, 使用 zip(), 去最短的序列questions = [‘name‘, ‘quest‘, ‘favorite‘]answers = [‘lancelot‘, ‘the‘, ‘blue‘, ‘abc‘]for q, a in zip(questions, answers):    print(q, a)# 反向遍曆集合for q in reversed(questions):    print(q)

enumerate返回的是一個迭代器對象, 裡麵包含一個yield, 可以返回函數的運行狀態

我們也可以使用yield來實現一個簡單的迭代器



04-python的列表操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.