1.列表:一个有序的集合(类似其它语言中的数组 具备函数功能)
list = [1,2,3]
length = len(list) #列表长度
total = sum(list) #列表求和
#列表截取
x = range(10) #列表[0,1,2,...9]
x[:3] #截取前三位 [0,1,2]
x[3:] #截取三位后的[3,4,..9]
x[-3:] #截取最后三位[7,8,9]
x[1:5] #[0,1,2,3,4]
2.元组:与列表类似(用圆括号表示或什么也不加)
tuple1 = (1,7)
tuple2 = 1,7
def sum_product(x, y):
return (x + y),(x * y)
sp = sum_product(3,3) #(6,9)
s,p = sum_product(3,3) #6,9
3.字典:类似java中的map
grades = { "Tom" : 88 , "Joe" : 95 }
Tom_grade = grades["Tom"] #取值
Tom_has_grade = "Tom" in grades #确认是否存在
Kate_grade = grades.get("Kate",0) #不存在则返回0
Jane_grade = grades.get("No one") #默认值为None
Num_Student = len(grades) #字典长度
grades.keys() #键的列表
grades.values() #值的列表
grades.items() #元祖的列表
defaultdict的使用
from collections import defaultdict
word_counts = defaultdict(int)
for word in document:
word_counts[word] += 1
4.集合:类似java中的set
s = set()
s.add(1)
s.add(2)
x = len(s) # 2
y = 2 in s # true
z = 3 in s # false
5 流程控制语句
if语句:
if 1 > 2:
message = "13551"
esif 1 > 3:
message = "12222"
else:
message = "121222"
一行语句中的if-then-else
x = "even" if y % 2 == 0 else "odd"
while循环:
x = 0
while x < 10
print x," is less than 10"
x += 1
for循环:
for x in range(10):
print x ,"is less than 10"
复杂循环
for x in range(10):
if x == 3
continue; #进入下次迭代
if x == 5
break; #完全退出循环
print x
6 . and or any all
s = some_function_that_return_a_String()
first_char = s and s[0] # 当s为true(s不为空)时 返回s[0]
y = a or b # 从左到右计算 返回第一个真值
list1 = [1 , 2 , 3 , 5]
list2 = [1 , {} , 3 , 5]
any(list1) # true
any(list2) # true
all(list1) # true
all(list2) # false
any([]) #true 列表中没有假的元素
all([]) #false 列表中没有真的元素