python關於for循環的幾個函數

1.enumerate:返回2個值,1是當前的for循環的第幾輪,2是循環獲得的數值java

enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence.git

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item

運行結果以下:ruby

Your choices are:
1 pizza
2 pasta
3 salad
4 nachos
None

 

2.zip:根據最小的列表,pairs它們app

It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.ide

zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.zip can handle three or more lists as well!oop

例子:ui

list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):
    # Add your code here!
    if a >= b:
        print a
    else: 
        print b

第一組獲得a=3 b=2 輸出3,第二組獲得a=9 b=4 輸出9。。。以此類推。this

 

3.For / else:for裏面有break時,else的內容不執行。spa

In this case, the else statement is executed after the for, but only if the for ends normally—that is, not with a break. This code will break when it hits 'tomato', so the else block won't be executed.code

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
        break
    print 'A', f
else:
    print 'A fine selection of fruits!'

 

ps:小練習題:

1.驗證一個數是整數:

def is_int(x):
    if int(x) == x:
        return True
    else:
        return False

 

 2.將相似於1234的數值加起來:1+2+3+4 = 10

方法1:轉換爲字符,將數字一個個取出來

def digit_sum(n):
    s = str(n)
    sum = 0
    for s1 in s:
        sum += int(s1)
    return sum 

方法2:使用%和/獲得一個個數字

def digit_sum(n):
    sum = 0
    while n > 0:
        sum += (n % 10)
        n = int(n / 10)
    return sum
        

 

3.迭代計算階乘

def factorial(x):
    f = 1
    while x > 1:
        f = f * x
        x -= 1
    return f

 

4.判斷是不是質數

def is_prime(x):
    if x == 1:
        return False
    elif x == 2:
        return True
    else:
        s = 2
        while s != x:
            if x % s == 0:
                return False
            s += 1
        else:
            return True

 

5.倒序輸出一個字符串:

def reverse(text):
    s = ""
    for i in range(0,len(text)):
        a = text[len(text) -1 - i]
        s = s + a
    return s

 

 6.返回輸入列表中不重複的內容:

def remove_duplicates(list):
    s = []
    for i in list:
            if i not in s:
                s.append(i)
    return s

 7.返回一個列表裏的中值:

def median(list):
    list_sorted = sorted(list)
    length = len(list_sorted)
    print list_sorted
    if length % 2 == 0:
        return float(list_sorted[length/2 - 1] + list_sorted[length/2])/2
    else:
        return list_sorted[length/2]
相關文章
相關標籤/搜索