Python學習筆記__3.2章 迭代

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

如果給定一個list或tuple,我們可以通過for迴圈來遍曆這個list或tuple,這種遍曆我們稱為迭代(Iteration)。

當然,不止 list 和 tuple 可以迭代。只要是可迭代對象,無論有無下標,都可以迭代都。包括dict 、str 、generator

 

在Python中,迭代是通過for ... in來完成的

 

1.1、字典的迭代

# 定義一個字典

d = {'a': 1, 'b': 2, 'c': 3}

 迭代 字典的key

for key in d:

 迭代 字典的value

for value in d.values():

 迭代 索引值對

for k, v in d.items()

1.2、字串迭代

for ch in 'ABC':

1.3、list迭代

# 定義一個list

L=[1,2,3]

 迭代 list的下標

for i in L:

    print(L.index(i))

 迭代list的值

for in L:

    print(i)

 迭代list的索引和元素本身  

for i, value in enumerate(L):    # enumerate函數 可以把一個list變成索引-元素對for i in L:

    print(L.index(i),i)

 兩個變數的迭代

 for x, y in [(1, 1), (2, 4), (3, 9)]:

 

2、例題

編寫一個函數,使用迭代尋找一個list中最小和最大值,並返回一個tuple:

# -*- coding: utf-8 -*-

def findMinAndMax(L):

 

    if len(L)==0:

        return (None, None)  

    min=L[0]

    max=L[0]

    for value in L:

        if value > max:

            max=value

        elif value < min:

            min=value

    return min,max

 

 

 

Python學習筆記__3.2章 迭代

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.