python特性语法之遍历、公共方法、引用
一、遍历
通过for。。。in。。。的语法结构,我们可以遍历字符串、列表、元组、字典等数据结构。
1、字符串遍历
a_str="helloworld"
forcharina_str:
print(char,end='')
2、列表遍历
a_list=[1,2,3,4,5]
fornumina_list:
print(num,end='')
3、元组遍历
a_tuple=(1,2,3,4,5)
fornumina_tuple:
print(num,end='')
4、字典遍历
1)遍历字典的key
dict={'name':'zhanshi','sex':'m'}
forkeyindict.keys():
print(key)
2)遍历字典的value
dict={'name':'zhanshi','sex':'m'}
forvalueindict.values():
print(value)
3)遍历字典的元素
dict={'name':'zhanshi','sex':'m'}
foritemindict.items():
print(item)
2)遍历字典的key-value
dict={'name':'zhanshi','sex':'m'}
forkey,valueindict.items():
print(key,value)
5、下标索引的遍历、enumerate()
chars=['a','b','c','d']
i=0
forcharinchars:
print('%d%s'%(i,char))
i+=1
enumerate()
chars=['a','b','c','d']
fori,charinenumerate(chars):
print(i,char)
二、公共方法(针对字符串、列表、元组、字典)
1、运算符
合并,除字典外,其他三种均支持
复制,除字典外,其他三种均支持
in元素是否存在,均支持,PS:对字典操作时,判断的是字典的键。
notin元素是否不存在,均支持
2、内置函数
cmp(item1,item2)比较两个值,PS:比较字典时,先比较键,再比较值。
len(item)计算容器中的元素个数,PS:操作字典时,返回的是键值对个数。
max(item)返回容器中元素最大值
min(item)返回容器中元素最小值
del(item)删除变量del变量【下标】del(变量名)
3、引用
在python中,值时靠引用来传递的。
可变类型与不可变类型
可变类型,值可以改变,地址不变:列表list,字典dict
不可变类型,值不可以改变,地址变化:数值类型(int,long,bool,float)、字符串(str)、元组(tuple)。
4、如何交换2个变量的值:1)a,b=b,a2)引用临时变量3)a=a+bb=a-ba=a-a