02学习Python

2018-08-10  本文已影响0人  zint

学习记录,欢迎指出错误

数据类型与变量

数据类型

在Python中标准的数据类型有六种:

变量

变量命名规则

Number(数字)

>>>a = 20
>>>print(type(a))
(class 'int)
>>>isinstance(a, int)
Ture

整数 int

Python可以处理任意大小的整数,包括正、负整数,在程序中的表示方法和数学上的写法一样。

浮点数 float

 浮点数也就是小数,之所以称为浮点数,是因为按照科学计数法表示时,一个浮点数的小数点位置是可变的。对于很大或很小的浮点数,就必须用科学计数法表示,用e代替10,如 123=1.23e2、0.012=1.2e-2
 整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算则可能会有四舍五入的误差。

布尔类型 bool

条件真为:Ture;条件假为:False

String(字符串)

Python中的字符串用 ' 或 " 括起来,同时使用反斜杠  \  转移特殊字符。语法格式:title = 'hello word'
字符串的截取语法格式为:title[0:5]

List(列表)

>>>list1=[ 123, 1.23,'abc' ]
>>>list2 = [ 456, 4.56, 'abcd', list1 ]
>>>list2[0] = 6
>>>list2
[6, 4.56, 'abcd',[123,1.23,'abc']]

Tuple(元组)

>>> a = (123,'a',2.4)
>>> a
(123, 'a', 2.4)
>>> print(a,type(a),len(a))
(123, 'a', 2.4) <class 'tuple'> 3
>>> print(a[1])
a
>>> a[0]=1#元素修改是不合法的
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> b = ()#创建一个空元组
>>> b
()
>>> c = (12,)创建一个元素的元组,需要在元素后面添加逗号
>>> c
(12,)
>>>

Set(集合)

>>> stu = {'a','b','c','d','a'}
>>> print(stu)#自动过滤掉重复的
{'a', 'b', 'c', 'd'}
>>> 'a' in stu#成员测试
True
>>> a = set( 'abcdefg')
>>> b = set( 'defghij')
>>> a
{'c', 'a', 'f', 'b', 'e', 'g', 'd'}
>>> a-b#a和b的差集
{'a', 'b', 'c'}
>>> a|b#a和b的并集
{'h', 'c', 'a', 'f', 'b', 'i', 'e', 'g', 'd', 'j'}
>>> a&b#a和b的交集
{'f', 'e', 'g', 'd'}
>>> a^b#a和b中不同时存在
{'h', 'j', 'c', 'b', 'a', 'i'}

Dictionaries(字典)

>>> dic = { }#创建一个空字典
>>> ple = { 'a':1, 'b':2, 'c':3  }
>>> ple
{'a': 1, 'b': 2, 'c': 3}
>>> ple['a']
1
>>> del ple['a'] #删除一个键值对
>>> ple
{'b': 2, 'c': 3}
>>> ple[ 'd' ]=4#添加一个键值对
>>> ple
{'b': 2, 'c': 3, 'd': 4}
>>> list(ple.keys())#返回所有key组成的list
['b', 'c', 'd']
>>> sorted(ple.keys())#按key排序
['b', 'c', 'd']
>>> 'b' in ple#成员测试
True
>>> 'a' in ple
False
>>> 'a' not in ple
Ture
数据类型比较
类型 语法格式 可变 下标读取
Number a = 60 N
String a = 'dream' N Y
List a = [ 60, 3.14, 'dream'] Y Y
Tuple a = ( 60, 3.14, 'dream' ) N Y
Sets a = { 60, 3.14, 'dream' } N N
Dictionary a = { 'dream' : 1, 'try' : 2 } a['try']

数据类型的转换

字符串常用方法

上一篇 下一篇

猜你喜欢

热点阅读