python学习笔记一:数据类型
一、Python文件类型1、源代码 hello.py: 1
2
)
然后执行: $ python compile.py
会生成二进制的 hello.pyc 文件 3、优化代码:经过优化的源文件,扩展名为 pyo 在命令行下执行下面的命令优化: $ python -O -m py_compile hello.py
二、python 变量? 三、python运算符1、整数除法 //? 即只取结果中的整数部分: >>> 3.0 // 2
1.0
>>> 3 // 2
1
>>>3**3
27
>>>3**2
9
3、逻辑与、逻辑或、逻辑非 >>> 1>2 3>2>>> 2>1 3>2>>>1>2 <span style="color: #0000ff;">or 3>2<span style="color: #000000;">
True >>>1>2 <span style="color: #0000ff;">or 1>3<span style="color: #000000;"> False >>> <span style="color: #0000ff;">not 1>2<span style="color: #000000;"> 4、运算符优先级: 四、python 数据类型1、数字:分整型、长整型、浮点、复数 其中复数(用j表示): >>> a=3.14j
>>>
2、字符串:单双引号一样 >>> str1=
>>> str2=
>>>140710100204544
>>>140710100204544
>>> mail=
>>> >>>
切片:[start:stop:step] 即:[开始索引:结束索引:步长值] 开始索引:同其它语言一样,从0开始。序列从左向右方向中,第一个值的索引为0,最后一个为-1 结束索引:切片操作符将取到该索引为止,不包含该索引的值。 步长值:默认是一个接着一个切取,如果为2,则表示进行隔一取一操作。步长值为正时表示从左向右取,如果为负,则表示从右向左取。步长值不能为0 注明:如果是string[ : ]的模式,那么就是[start:stop] 示例: >>>exam=
>>> exam[:-1>>> exam[2>>> exam[:7:2>>> exam[:3:-1
3、列表:处理一组有序项目的数据结构,是可变类型数据,用[]表示,包括了多个以逗号隔开的项目。 >>> l=[,25,>>>,>>>
空列表: >>>l=[]
只有一个值: >>>l=[]
列表常用方法: 取值:list[index] 或者 list[start:end:offset] 追加:list.append(x); 追加列表:list.extend([x,y]);结果为[...,x,y], 删除:del(list[index]) 或者 list.remove(list[index]) 修改:list[index]=x 查找:var in list >>>l=[,1>>> >>>
4、元组:跟列表类似,只是跟字符串一样是不可变的,即你不能修改元组(只能在内存中重新创建一个)。
>>>userinfo=(,30,>>>
>>>t=()
>>>t=(1,)
>>>,>>> name,age,gender=>>>
>>>25
>>>
>>><span style="color: #000000;">a 1 <span style="color: #000000;">b 2 <span style="color: #000000;">c 3 5、字典:python中唯一的映射类型(哈希表)
>>>dic={0:0,:>>>>>>dic[
>>> fdict=dict([(,1),(,2>>>: 2,: 1}
>>> d={}.fromkeys((,,0),-1>>>: -1,: -1,0: -1}
字典常用方法: (1)、使用键值访问更新 (2)、del dict1['a']删除字典中键值为a的元素 (3)、dict1.pop('a') 删除并返回键为'a'的元素 (4)、dict1.clear()删除字典所有元素 (5)、del dict1 删除整个字典 (6)、str(dict1) 转换为字符串 (7)、get(key[,msg]) 如果key不存在返回msg(没有为空)值 (8)、dict1.items() 返回键值对元组的列表 >>>: 1,: 2>>>,(,2)]
(9)、dict1.keys() 返回字典中键的列表 >>>: 1,: 2>>>,]
(10)、dict1.setdefault(key,default=None) 若key存在则返回其value,否则dict1[key]=default (11)、dict1.update(dict2) 将dict2中的键值对添加到字典dict1中,如果有重复就覆盖,否则添加。 (12)、len(dict1) 返回字典中有多少项 >>>: 1,: 2>>>2
切片:序列后跟一个方括号,方括号中有一对用冒号隔开的可选数字,数字是可选的,冒号是必须的。如: >>>exam=
exam[:-1>>> exam[2>>> exam[:7:2>>> exam[:3:-1
>>>exam=
五、序列基本操作1、len:序列长度 >>>exam=
3
>>>str1=
str2=
str1+
>>>str1=
str1*3
>>>str1=
>>>
5、max:返回最大值 >>>s=
'5'
>>>s=
'1'
>>>str1=
str2=
1
<span style="color: #800000;">1<span style="color: #800000;">' <span style="color: #000000;">cmp(str1,str2) -1 <span style="color: #800000;">123<span style="color: #800000;">' <span style="color: #000000;">cmp(str1,str2) 0 六、 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |