Python_9_Codecademy_9_Lists and Functions

weixin_34402408發表於2016-04-20

<a href="http://www.jianshu.com/p/54870e9541fc">總目錄</a>


課程頁面:https://www.codecademy.com/
內容包含課程筆記和自己的擴充套件折騰


Lists

  • 複製lists: list * n
n = ["ZHANG.Y"]
n = n * 5
print n
Output:
['ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y']
  • List elements modification
n = [1, 6, 9]
n[1] = n[1] * 3
print n

Output:
[1, 18, 9]

  • Appending a new element
n = [1, 6, 9]
n.append(12)
print n

Output:
[1, 6, 9, 12]

  • list.pop(index)
n = [1, 6, 9]
x = n.pop(2)
print x
print n

Output:
9
[1, 6]

  • list.remove(item)
n = [1, 6, 9]
n.remove(9)
print n

Output:
[1, 6]

  • del(list[index])
n = [1, 6, 9]
del(n[2])
print n

Output:
[1, 6]

  • range(start, stop, step)
print range(8)
print range(1, 8)
print range(1, 8, 2)

Output:
[0, 1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[1, 3, 5, 7]

  • 合併lists:list1 + list2
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print list3

Outpt:
[1, 2, 3, 4, 5, 6]

  • list裡面巢狀lists
list_A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in list_A:
    print i

Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

  • 練習:設計一個function,把類似[[1, 2, 3], [1, 3, 5, 7, 9]]這樣的list變成[1, 2, 3, 1, 3, 5, 7, 9]
    【方法一】
def flatten(my_list):
    results = []
    for i in my_list:
        for item in i:
            results.append(item)
    return results 
print flatten([[1, 2, 3], [1, 3, 5, 7, 9]])

【方法二】

def flatten(my_list):
    results = []
    for i in my_list:
        for number in range(len(i)):
            results.append(i[number])
    return results
print flatten([[1, 2, 3], [1, 3, 5, 7, 9]])

Output:
[1, 2, 3, 1, 3, 5, 7, 9]

  • .join(list)
    把list中的items連起來
my_list = ['ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y']
print " <3 ".join(my_list)
Output:
ZHANG.Y <3 ZHANG.Y <3 ZHANG.Y <3 ZHANG.Y <3 ZHANG.Y

Functions

  • More than one variables:
def addition(a, b):
    return a + b
print addition(1, 2)

Output:
3

  • A list as an argument
def print_first_item(items):
    print items[0]
n = [1, 6, 9]
print_first_item(n)

Output:
1

  • Print items one by one
# 簡單方法:
def print_items(items):
    for x in items:
        print x
n = [1, 6, 9] 
print_items(n)
def print_items(items):
    for x in range(len(items)):
        print items[x]  
n = [1, 6, 9] 
print_items(n)

Output:
1
6
9

  • Modifying each element
def triple_list(my_list):
    for x in range(len(my_list)):
        my_list[x] = my_list[x] * 3
    return my_list
n = [1, 6, 9] 
# 比較
triple_list(n)
print n
print triple_list(n)

Output:
[3, 18, 27]
[9, 54, 81]

相關文章