python入门(五)序列和字典
参考书籍 python_note_pdq.pdf
7.1 序列
letters = (1,)
print(letters,":",type(letters))
letters = (1)
print(letters,":",type(letters))
letters = (1,2,3,4,5,6)
print(letters,":",type(letters))
#用索引找寻元素和片段
print(letters[0],":",letters[1:3])
#不能直接修改0号的元素,只能通过如下方法修改
letters = (16,) + letters[1:]
print(letters)
控制台返回信息:
(1,) : <class 'tuple'>
1 : <class 'int'>
(1, 2, 3, 4, 5, 6) : <class 'tuple'>
1 : (2, 3)
(16, 2, 3, 4, 5, 6)
7.2 序列赋值
#python交换几个变量值的YD方法
a = 1
b = 2
c = 3
a,b,c=c,b,a
print(a,b,c)
a,b,c=a*b,b*c,a+b+c
print(a,b,c)
控制台返回信息:
3 2 1
6 2 6
7.3 序列作为返回值
def swap1(x,y):
return y,x
a,b=(1,2)
print(a,type(a),b,type(b))
print(swap1(a,b))
def swap2(x, y):
x, y = y, x
a = 1
b = 2
swap2(a, b)
print(a, b)
打印的结果:
1 <class 'int'> 2 <class 'int'>
(2, 1)
1 2
在Python中如果变量具有相同的值,就可以认为这些变量是同一个值的别名。也就是这些变量指向同一个
值。这样做的好处也许是节省了内存空间。但是如果某一个变量改变了它自己的值,那么解释器就开辟出新内存空间存储这个变量的值。这个变量就指向新的值。
a = 1
b = 1
print(id(a),id(b))
a = 13
print(id(a),id(b))
打印信息:
505389048 505389048
505389240 505389048
7.4 随机函数
import random
for i in range(3):
print(random.random())
打印结果如下:
0.868696815445
0.280806794298
0.349025563434
7.5 随机数列表
import random
def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random();
return s
print(randomList(2))
打印输出信息:
[0.5529235083808711, 0.9325466671041306]
7.6 计数
import random
def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random();
return s
def inBucket(list,low,high):
count = 0
for num in list:
if(low < num < high):
count = count + 1
return count
print(inBucket(randomList(2000),0.0,0.5))
计算了出线在0---0.5之间的几率,控制台打印信息1003
7.7 分割范围
import random
#产生随意数列
def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random();
return s
#检查在某范围的随机数的个数
def inBucket(list,low,high):
count = 0
for num in list:
if(low < num < high):
count = count + 1
return count
#产生大量范围看分布
def rangeBucket(numBuckets,list):
buckets = [0] * numBuckets
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
buckets[i] = inBucket(list, low, high)
return buckets
print(rangeBucket(20,randomList(2000)))
后台打印结果如下:
[105, 94, 100, 89, 98, 97, 112, 93, 109, 106, 96, 106, 97, 103, 104, 108, 96, 90, 99, 98]
8.0 字典
字典类似于组合类型,但是字典可以用整数和字符串来走索引,而组合类型只能用整数。
dict1 = {'mother': '妈妈', 'father': '爸爸'}
print(dict1," ",type(dict1))
dict2 = {1:'mother',2:'father'}
print(dict2," ",type(dict2))
dict3 = {}
#新增字典元素
dict3["test"]="测试"
dict3["hand"]="手"
#用key来访问对应的值,有点像java的map
print(dict3," ",dict3["test"])
dict3["test"]="测试(中文)"
print(dict3)
控制台返回信息:
{'father': '爸爸', 'mother': '妈妈'} <class 'dict'>
{1: 'mother', 2: 'father'} <class 'dict'>
{'test': '测试', 'hand': '手'} 测试
{'test': '测试(中文)', 'hand': '手'}
8.1字典操作
inventory = {'apples':430,'bananas':312,'oranges':525}
#del删除元素
del inventory['apples']
print(inventory)
#len返回字典元素的数量
print(len(inventory))
#clear方法,删除所有元素
inventory.clear()
print(inventory)
控制台消息:
{'oranges': 525, 'bananas': 312}
2
{}
8.2 别名和拷贝
opposites = {'up': 'down', 'right': 'wrong',\
'true': 'false'}
alias=opposites
print(id(alias)," ",id(opposites))
copy=opposites.copy()
print(id(copy)," ",id(opposites))
alias['right'] = 'left'
print(alias," ",opposites)
alias = (1,2,3)
print(alias," ",opposites)
控制台信息如下:
12173008 12173008
12877664 12173008
{'right': 'left', 'true': 'false', 'up': 'down'} {'right': 'left', 'true': 'false', 'up': 'down'}
(1, 2, 3) {'right': 'left', 'true': 'false', 'up': 'down'}
其中alias是别名,如果alias[0]元素改变,opposites[0]也会改变;而copy就是拷贝。
8.3 稀疏矩阵
matrix = [
[0,0,0,1,0],
[0,0,0,0,0],
[0,2,0,0,0],
[0,0,0,0,0],
[0,0,0,3,0] ]
#列表表示矩阵
print(matrix," ",type(matrix))
#字典表示举证,只指出非零的值
matrix = {(0,3): 1, (2, 1): 2, (4, 3): 3}
print(matrix," ",type(matrix))
#get方法得到值
print(matrix.get(0,3)," ",matrix.get(0,0))
控制台打印信息:
[[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]] <class 'list'>
{(0, 3): 1, (4, 3): 3, (2, 1): 2} <class 'dict'>
3 0
8.4 暗示
import time
#这个函数很耗时,n越大,计算次数越多
def fibonacci1(n):
if n == 0 or n == 1:
return 1
else:
return fibonacci1(n-1) + fibonacci1(n-2)
previous = {0:1, 1:1}
def fibonacci2(n):
if n in previous:
return previous[n]
else:
newValue = fibonacci2(n-1) + fibonacci2(n-2)
#每次计算把值追加到字典中了
previous[n] = newValue
return newValue
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci1(31)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci1(32)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci2(50)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci2(60)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
后台打印信息如下:
2010-01-13 20:22:07
2010-01-13 20:22:09
2010-01-13 20:22:13
2010-01-13 20:22:13
2010-01-13 20:22:13
貌似long和int长度的问题在python3里面没有出现,这里先不关心了。
由于这本电子书是python2的版本吧,我安装的是python3,所以可以在这里查询下差别:
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html
8.5 计算字符串
letterCounts = {}
for letter in "Mississippiasdf":
#get后一个参数是给了个默认值
letterCounts[letter] = letterCounts.get(letter,0) + 1
print(letterCounts)
后台打印输出:
{'a': 1, 'd': 1, 'f': 1, 'i': 4, 'M': 1, 'p': 2, 's': 5}
参考书籍 python_note_pdq.pdf
7.1 序列
letters = (1,)
print(letters,":",type(letters))
letters = (1)
print(letters,":",type(letters))
letters = (1,2,3,4,5,6)
print(letters,":",type(letters))
#用索引找寻元素和片段
print(letters[0],":",letters[1:3])
#不能直接修改0号的元素,只能通过如下方法修改
letters = (16,) + letters[1:]
print(letters)
控制台返回信息:
(1,) : <class 'tuple'>
1 : <class 'int'>
(1, 2, 3, 4, 5, 6) : <class 'tuple'>
1 : (2, 3)
(16, 2, 3, 4, 5, 6)
7.2 序列赋值
#python交换几个变量值的YD方法
a = 1
b = 2
c = 3
a,b,c=c,b,a
print(a,b,c)
a,b,c=a*b,b*c,a+b+c
print(a,b,c)
控制台返回信息:
3 2 1
6 2 6
7.3 序列作为返回值
def swap1(x,y):
return y,x
a,b=(1,2)
print(a,type(a),b,type(b))
print(swap1(a,b))
def swap2(x, y):
x, y = y, x
a = 1
b = 2
swap2(a, b)
print(a, b)
打印的结果:
1 <class 'int'> 2 <class 'int'>
(2, 1)
1 2
在Python中如果变量具有相同的值,就可以认为这些变量是同一个值的别名。也就是这些变量指向同一个
值。这样做的好处也许是节省了内存空间。但是如果某一个变量改变了它自己的值,那么解释器就开辟出新内存空间存储这个变量的值。这个变量就指向新的值。
a = 1
b = 1
print(id(a),id(b))
a = 13
print(id(a),id(b))
打印信息:
505389048 505389048
505389240 505389048
7.4 随机函数
import random
for i in range(3):
print(random.random())
打印结果如下:
0.868696815445
0.280806794298
0.349025563434
7.5 随机数列表
import random
def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random();
return s
print(randomList(2))
打印输出信息:
[0.5529235083808711, 0.9325466671041306]
7.6 计数
import random
def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random();
return s
def inBucket(list,low,high):
count = 0
for num in list:
if(low < num < high):
count = count + 1
return count
print(inBucket(randomList(2000),0.0,0.5))
计算了出线在0---0.5之间的几率,控制台打印信息1003
7.7 分割范围
import random
#产生随意数列
def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random();
return s
#检查在某范围的随机数的个数
def inBucket(list,low,high):
count = 0
for num in list:
if(low < num < high):
count = count + 1
return count
#产生大量范围看分布
def rangeBucket(numBuckets,list):
buckets = [0] * numBuckets
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
buckets[i] = inBucket(list, low, high)
return buckets
print(rangeBucket(20,randomList(2000)))
后台打印结果如下:
[105, 94, 100, 89, 98, 97, 112, 93, 109, 106, 96, 106, 97, 103, 104, 108, 96, 90, 99, 98]
8.0 字典
字典类似于组合类型,但是字典可以用整数和字符串来走索引,而组合类型只能用整数。
dict1 = {'mother': '妈妈', 'father': '爸爸'}
print(dict1," ",type(dict1))
dict2 = {1:'mother',2:'father'}
print(dict2," ",type(dict2))
dict3 = {}
#新增字典元素
dict3["test"]="测试"
dict3["hand"]="手"
#用key来访问对应的值,有点像java的map
print(dict3," ",dict3["test"])
dict3["test"]="测试(中文)"
print(dict3)
控制台返回信息:
{'father': '爸爸', 'mother': '妈妈'} <class 'dict'>
{1: 'mother', 2: 'father'} <class 'dict'>
{'test': '测试', 'hand': '手'} 测试
{'test': '测试(中文)', 'hand': '手'}
8.1字典操作
inventory = {'apples':430,'bananas':312,'oranges':525}
#del删除元素
del inventory['apples']
print(inventory)
#len返回字典元素的数量
print(len(inventory))
#clear方法,删除所有元素
inventory.clear()
print(inventory)
控制台消息:
{'oranges': 525, 'bananas': 312}
2
{}
8.2 别名和拷贝
opposites = {'up': 'down', 'right': 'wrong',\
'true': 'false'}
alias=opposites
print(id(alias)," ",id(opposites))
copy=opposites.copy()
print(id(copy)," ",id(opposites))
alias['right'] = 'left'
print(alias," ",opposites)
alias = (1,2,3)
print(alias," ",opposites)
控制台信息如下:
12173008 12173008
12877664 12173008
{'right': 'left', 'true': 'false', 'up': 'down'} {'right': 'left', 'true': 'false', 'up': 'down'}
(1, 2, 3) {'right': 'left', 'true': 'false', 'up': 'down'}
其中alias是别名,如果alias[0]元素改变,opposites[0]也会改变;而copy就是拷贝。
8.3 稀疏矩阵
matrix = [
[0,0,0,1,0],
[0,0,0,0,0],
[0,2,0,0,0],
[0,0,0,0,0],
[0,0,0,3,0] ]
#列表表示矩阵
print(matrix," ",type(matrix))
#字典表示举证,只指出非零的值
matrix = {(0,3): 1, (2, 1): 2, (4, 3): 3}
print(matrix," ",type(matrix))
#get方法得到值
print(matrix.get(0,3)," ",matrix.get(0,0))
控制台打印信息:
[[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]] <class 'list'>
{(0, 3): 1, (4, 3): 3, (2, 1): 2} <class 'dict'>
3 0
8.4 暗示
import time
#这个函数很耗时,n越大,计算次数越多
def fibonacci1(n):
if n == 0 or n == 1:
return 1
else:
return fibonacci1(n-1) + fibonacci1(n-2)
previous = {0:1, 1:1}
def fibonacci2(n):
if n in previous:
return previous[n]
else:
newValue = fibonacci2(n-1) + fibonacci2(n-2)
#每次计算把值追加到字典中了
previous[n] = newValue
return newValue
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci1(31)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci1(32)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci2(50)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
fibonacci2(60)
print(time.strftime("%Y-%m-%d %H:%M:%S"))
后台打印信息如下:
2010-01-13 20:22:07
2010-01-13 20:22:09
2010-01-13 20:22:13
2010-01-13 20:22:13
2010-01-13 20:22:13
貌似long和int长度的问题在python3里面没有出现,这里先不关心了。
由于这本电子书是python2的版本吧,我安装的是python3,所以可以在这里查询下差别:
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html
8.5 计算字符串
letterCounts = {}
for letter in "Mississippiasdf":
#get后一个参数是给了个默认值
letterCounts[letter] = letterCounts.get(letter,0) + 1
print(letterCounts)
后台打印输出:
{'a': 1, 'd': 1, 'f': 1, 'i': 4, 'M': 1, 'p': 2, 's': 5}