<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]