python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍

  对于python而言,一切事物都是对象,对象是基于类创建的,对象继承了类的属性,方法等特性    

1.int

  首先,我们来查看下int包含了哪些函数

# python3.x
dir(int)
# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']


# python 2.x
dir(int)
# ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

 

# __abs__()  绝对值输出
num = 1
result = num.__abs__()

print(result)

num = -1
result = num.__abs__()
print(result)
__abs__() 绝对值输出
1 num = -1
2 result = num.__add__(2)
3 
4 print(result)
5 
6 # 打印结果将输出 1
__add__加法
1 num = 5
2 result = num.__and__(2)
3 print(result)
4 
5 #打印输出为0
6 # 0 0 0 0 0 1 0 1    5
7 # 0 0 0 0 0 0 1 0    2
8 #相同位为1则为1,由于没有相同位,所以5 & 2结果为0
__and__ 与&运算
1 # 以下结果输出都是True
 2 num = 11
 3 print(num.__bool__()) # True
 4 
 5 num = -11
 6 print(num.__bool__()) #True
 7 
 8 # 以下结果输出都是 False
 9  num = 0
10 print(num.__bool__()) #False
11 
12 num = None
13 num = False
14 print (num.__bool__()) # False
__bool__ 布尔值
#通过divmod函数可以实现将一个int类型对象除以另一个int对象得到一个两个元素的列表,
#列表左边为除尽取整的值,第二个元素为取模的余数

num = 9
result = num.__divmod__(2)
print(result)

#输出(4,1)
__divmod__ 除法取整取模
num = 2
result = num.__eq__(3)
print(result)

#打印结果为False
#2 == 3   结果为假

result = num.__eq__(2)
print(result)
#打印结果为True
# 2 == 2 结果为真

__eq__ ==比较运算符
__eq__ ==比较运算符
num = 9
print(num.__float__())

#打印结果为 9.0
__float__ 转换为浮点数
num = int(181)
result = num.__floordiv__(9)
print(result)

#打印输出20
#地板除 //取整

__floordiv__地板除//
__floordiv__地板除//
num = int(181)
result = num.__getattribute__("bit_length")
print(result)

#打印输出 <built-in method bit_length of int object at 0x100275020>
#说明该数据类型num存在bit_length这个属性,可以用于判断对象是否拥有某种属性
__getattribute__获取对象属性
num = int(181)
print(num.__ge__(111))
#打印输出结果为True
#因为181大于111,所以结果为真,该属性用于判断大于等于该属性自身的方法,结果将返回真,否则为假
__ge__ 比较运算>=
num = 181
print(int.__invert__(num))
#打印输出-182

num = -180
print(int.__invert__(num))
#打印输出179

num = -181
print(int.__invert__(num))
#打印输出180
__invert__ 非~运算
num = -181
result = num.__le__(111)
print(result)
#打印输出结果为True
#当传人参数与对象本身相比较,只要对象小于或者等于传人的参数,则结果为真,否则为假
__le__ 小于等于
num = -181

result = num.__lshift__(1)
print(result)
#打印输出结果为-362   ,即-181 *( 2**1)

result = num.__lshift__(2)
print(result)
#打印输出结果为-724 ,即-181*(2**2)


#当传入参数大于等于0时且对象本身不能为0,首先参数本身为2的指数幂运算,然后再与对象本身相乘结果则为左移最终结果
__lshift__左移运算
num = -181
print(num.__lt__(11))
 
#打印输出结果为True
 
#凡是对象比传入的参数小,则结果为真,否则结果为假
__lt__小于
num = -181
print(num.__mod__(3))
 
#打印输出结果为2,因为-181除以3等于60,余数为2,所以结果为2
__mod__取模运算
num = 181
print(num.__mul__(2))

#打印输出结果为362,即181*2的结果
__mul__ 乘法运算
num = -181
print(int.__neg__(num))
 
#打印结果为181,即-(-181),结果为181
__neg__一元运算减法
num = 181
print(num.__ne__(181))
#打印结果为False

print(num.__ne__(11))
#打印结果为True

#凡是传入参数与对象本身不相等,则结果为真,否则为假
__ne__ 不等于比较
num = 18
print(num.__or__(7))

#打印输出结果为23
# 0 0 0 1 0 0 1 0     18
# 0 0 0 0 0 1 1 1       7
# 0 0 0 1 0 1 1 1      23
位的或运算,凡是相同位有一位为真,即为1,则结果为真,即1,然后所以最终结果为23
__or__ 或|运算
num = 9
print(num.__pow__(2))
#打印输出结果为81,即9**2
__pow__ 幂运算
num = 6
print(num.__rdivmod__(3))
#返回结果(0,3) 左边为余数,右边为整除的结果
__rdivmod__ 与divmod返回的结果相反
#python 2.7
num = 1
print(num.__sizeof__())
#打印输出结果为24个字节,说明一个int类型默认就在内存中占用了24个字节大小

#python3.5
num = 1
print(num.__sizeof__())
#打印输出结果为28个字节,说明一个int类型数据默认在内存中占用了24个字节大小
__sizeof__ 计算数据类型占用内存大小
num = int(1111)
result = num.__str__()
print(type(result))

#打印输出结果为<class 'str'>
#将int类型转换为str数据类型
__str__ int转换成str
num = int(9)
print(num.__sub__(2))

#打印输出结果为7
#对象本身减去传入参数,得到最终的返回值
__sub__ 减法运算
num = 11
print(num.__truediv__(3))

#打印输出结果为3.6666666666666665
#返回的数据类型为float,浮点型
__truediv__ 真除
num = 10
print(num.__xor__(6))

# 0 0 0 0 1 0 1 0  10
# 0 0 0 0 0 1 1 0  6
# 0 0 0 0 1 1 0 0  12

#同位比较,都是0则为假,都是1则为假,一真一假为真
__xor__ 异或^运算
num = 5
print(num.bit_length())
#打印输出结果为3

# 0 0 0 0 0 1 0 1   #长度为3位
bit_length 显示数据所占位长度
num = 2.3 - 2.5j
result = num.real       #复数的实部
print(result)   #打印输出2.3
result = num.imag    #复数的虚部
print(result)   #打印输出2.5j

result = num.conjugate()   #返回该复数的共轭复数
print(result)  #打印输出(2.3+2.5j)
conjugate
num = 5
print(num.__format__("20"))
#表示5前面讲话有20个空格
__format__ 格式化输出
print(int.from_bytes(bytes=b'1', byteorder='little')
 
 
#打印输出 49  ,即将字符1转换为十进制
from_bytes 字符转换十进制
num = 2
result = num.to_bytes(5,byteorder='little')
print(result)
#打印输出b'\x02\x00\x00\x00\x00'
for i in result:
    print(i)


#打印输出2\n0\n0\n0\n0
#\n表示回车
to_bytes int转换为字节

 

 

 

2.str

1 #python3.5
2 dir(str)
3 #['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
4 
5 #python2.7
6 dir(str)
7 #['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

 

 

 

strA = "hello"
print(strA.__add__(" world"))
#输出hello world
__add__ 字符串拼接
strA = "hello"
print(strA.__contains__("h"))
#True

print(strA.__contains__('hex'))
#False
__contains__ 包含判断
strA = "hello"
print(strA.__eq__('hello'))
#True

print(strA.__eq__('hellq'))
#False
__eq__ 字符串==比较
strA = "hello"
print(strA.__getattribute__('__add__'))
#<method-wrapper '__add__' of str object at 0x101d78730>
 
#判断对象是否包含传入参数的属性
__getattribute__获取对象属性
strA = "hello"
print(strA.__getitem__(0))
#输出下标为0的字符  h
#超出下标会报错的
__getitem__获取对应字符
 strA = "hello"
print(strA.__getnewargs__())
#打印输出 ('hello',)
#将字符类型转换为元组方式输出
__getnewargs__转换成元组
strA = "hello"
print(strA.__ge__('HELLO'))
print(strA.__ge__('Hello'))
print(strA.__ge__('hello'))
#以上结果都为True,
print(strA.__ge__('hellq'))
#以上结果为假
__ge__ 字符串比较
strA = 'Hello'
print(strA.__gt__('HellO'))
#打印输出True

#字符串比较的是传入的参数每个字符首先得包含对象,其次如果字符串之间比较,大写比小写大,,如果传入参数都为大写,且对象也都为大写,那么结果为假,字符串比较首先比较的是字符串是否相同,不相同则为假,再次每个字符进行比较,只要前面有一位大于对方,则不继续比较了


#比如 HelLo与HEllo,首先两个字符串都是一样的,然后再比较第一位,第一位也一样,再比较第二位,大写比小写大,所以第二个字符串大,就不会继续比较下去了
__gt__ 字符串大于判断
strA = "hello"
print(strA.__hash__())
#-7842000111924627789
__hash__ 生成一个临时的hash值
strA = "hello"
result = strA.__iter__()
for i in result:
    print(i)

#打印输出
#h
#e
#l
#l
#o
__iter__ 字符串迭代
strA = 'hello'
print(strA.__len__())
 
#打印输出结果为5
__len__ 判断字符串长度
strA = 'Hello'
print(strA.__le__('ello'))
#True


#字符串小于运算比较,先比较对象是否包含传入参数,当包含则再比较相同位的字母,大小字母比小写字母大,当前面有一位比较出谁大谁小了,则不再继续比下去了

__le__小于等于
strA = 'hello'
print(strA.__lt__('ello'))
#True

#字符串小于比较与小于等于比较类似,唯一一点是小于比较时,对象与传入的参数大小写不能完全一样

__lt__ 小于
strA = 'hello'
print(strA.__mul__(3))
#hellohellohello


#打印结果将输出三个hello

__mul__ 乘法运算
__le__小于等于
strA = "hello"

print(strA.__ne__('HEllo'))
#True


#字符串不等于运算比较,凡是对象与传入参数只要有一个字母大小写不一样则为真,否则为假
__ne__ 不等于比较
strA = "HELLO"
print(strA.zfill(6))
#0HELLO


#当传入的参数长度比对象长度大时,多余的长度则以0进行填充
zfill 以0填充
strA = "hELlo1112123"
print(strA.upper())
#HELLO

#将所有的字母转换为大写
upper 字母转换大写
print("hello world".title())
 
#Hello World

#每个单词首字母大写输出,且单词的第二位后面都会变成小写,如helLO,最终会格式化为Hello
title 标题
print("hEllO".swapcase())
#HeLLo

#将原来的大小字母转换成小写字母,小写转换成大小字母
swapcase 大小写转换
print("    hello   world   ".strip())
#hello   world
#将字符串两边的空格去掉
strip 去除字符串两边的空格
print("hello".startswith('h'))
#True

print("hello".startswith('h',1))
#False

#startswith这个函数可以指定起始位置进行判断字符是否存在
startswith 字符串是否存在该字符
print("hello\nworld".splitlines())
#['hello','world']

#splitlines默认以\n换行符进行分割字符,最终返回一个列表
splitlines 以换行符分割字符串
print("hello world".split())
#['hello','world']

print("hello world".split('\n'))
#['hello world',]

#默认以空格分割字符串,可以指定分隔符
split 默认以空格分割字符
print("  hello  world    ".rstrip())
 
#  hello  world
#打印将会把world后面的空格去除
rstrip 去除右边的空格
print("hello world".rpartition('he'))
#('', 'he', 'llo world ')
#只返回传入参数且存在字符串里的字符然后组合成一个新的元组
rpartition 返回字符串的一部分
print("hello world".rjust(20))
#         hello world
#默认以空格填充,从左到最后一个单词d结尾一个长度为20,也就是说h前面有9个空格

print("hello world".rjust(20,'+'))
#+++++++++hello world
#这里以‘+’填充,对比上面,可以看的更具体,前面有9个+被用来填充
rjust 向右偏移
 print("hello world".rindex('wo'))
#6
#通过查找字符串'wo'获取该字符串在hello world 里面的下标位置,这里从左往右数,第七个位置,字符串的下标默认从0开始,所以返回6
#当找不到时则抛出异常
rindex 查找下标
strA = 'hello 123'
table1 = str.maketrans('123','我很好')
print(strA.translate(table1))
#hello 我很好

#将字符串里面的123通过table进行翻译成对应的值,table1的123长度必须和‘我很好长度对应’


strA = 'hello 12'
table1 = str.maketrans('123','我很好')
print(strA.translate(table1))
#hello 我很
translate 翻译
print("hello".rfind('e'))
#1

print("hello".rfind('ee'))
#-1

如果找到,则结果为对应的下标,否则返回-1
rfind 从左到右查找
print('hello world'.replace('e','o'))
#hollo world
#将字符串里面所有的e替换成o,区分大小写
replace 字符串替换
print('hello world'.rpartition('el'))
#('h', 'el', 'lo world')
#效果与rpartition相似
partition 截取字符串
table1 = str.maketrans('123','我很好')
print(table1)
#{49: 25105, 50: 24456, 51: 22909}
#首先传入的必须是两个参数,且长度相等
#返回结果将是一个字典类型,每一个字符串将会映射到第二个参数的相同位置的字符串上,
#当这里存在三个参数时,第三个参数必须是一个字符串类型,且整个字符串将被映射成None

strA = 'hello 1233飒飒'
table1 = str.maketrans('123','我很好','飒飒')
print(strA.translate(table1))
print(table1)

#以下为输出结果
#hello 我很好好
#{49: 25105, 50: 24456, 51: 22909, 39122: None}

#这个字典的值将被映射成unicode值,如49表示unicode的1
maketrans 翻译表
print("   hello world   ".lstrip())
#hello world
将hello左边空格去除
lstrip 去除左边的空格
print("HELLo22".lower())
#hello22
#将所有字母转换为小写
lower 转换小写
print("hello world".ljust(20,'+'))
#hello world+++++++++
#从右向左开始进行填充,总长度为20
ljust 右填充
print('+'.join(('hello','world')))
#hello+world
#通过一个字符串去与join里面的一个迭代器里的字符串进行联结生存一个新的字符串
join 生存一个字符串
print('Hello'.isupper())
print('HELLO1'.isupper())
#False
#True

#判断所有的字母是否都是大小,是则返回真,否则假
isupper 是否全部大小
print('Hello'.istitle())
print('Hello world'.istitle())
#True
#False
#判断每个单词首字母是否大写,是则为真,否则为假
istitle 是否是标题
print(' hello'.isspace())
print(' '.isspace())
#False
#True
#判断内容是否为空格
isspace 是否是空格
print('hello world'.isprintable())
print('\n'.isprintable())
#True
#False
#由于换行符是特殊字符,不可见,所以不能被打印,结果为假
issprintable 是否可以被打印
print('111'.isnumeric())
print(''.isnumeric())
print('1q'.isnumeric())
#True
#True
#False
#True包含unicode数字,全角数字(双字节),罗马数字,汉字数字
isnumeric 是否是数字
print('Hello'.islower())
print('hello'.islower())
#False
#True
#判断字母是不是都是小写,是则为真,否则为假
islower 是否是小写
print('def'.isidentifier())
print('hello'.isidentifier())
print('2a2'.isidentifier())
#True
#True
#False

#用来检测标识符是否可用,也就是说这个名字能不能用来作为变量名,是否符合命名规范,如果符合则为真
#通常会结合keyword.iskeyword()这个方法去在做判断是否是关键字,防止因命名不规范导致某些内置功能不可用
isidentifier
print('hello'.isdigit())
print('111e'.isdigit())
print(''.isdigit())
print('121'.isdigit())

#False
#False
#False
#True

#unicode数字,全角数字(双字节),byte数字,罗马数字都为真
isdigit 是否是数字
print('11'.isdecimal())
print(''.isdecimal())
print('11d'.isdecimal())
#
#True
#False
#False
#只有全部为unicode数字,全角数字(双字节),结果才为真
isdecimal 是否是数字
print('hee'.isalpha())
print('Hello'.isalpha())
print('1212'.isalpha())
print('hhee1'.isalpha())
#True
#True
#False
#False
#当结果都是字母则为真,否则为假
isalpha 是否是字母
print('hew11'.isalnum())
print('HHH'.isalnum())
print('112'.isalnum())
print('  q '.isalnum())
print('!!@~d'.isalnum())
#True
#True
#True
#False
#False

#当结果为任意数字或字母时,结果为真,其他字符为假
isalnum 是否为数字或字母
print('hello'.index('e'))
print('hello'.index('el'))
print('hello'.index('el',1))
#1
#1
#1
#通过查找制定的字符获取对应字符串的下标位置,可以指定起始位置,第3个事咧则表示从下标1开始查找,包括下标1的位置,如果指定end的结束位置,查找是不包括end的位置本身
index 通过字符查找下标
print('hello'.find('h',0))
print('hello'.find('h',1))
#0
#-1

#find是从下标0位置开始找起,包含开始的位置0,如果有结束的位置,不包含结束位置,查找到则显示具体下标位置,否则显示-1
find查找字符串下标
print('hello{0}'.format(' world'))
print('hello{0}{1}'.format(' world',' python'))
print('hello{name}'.format(name=' world'))
#hello world
#hello world python
#hello world
format 格式化输出字符串
print('hello\tworld'.expandtabs(tabsize=8))
#hello   world  指定制表符长度为8
expandtabs 制表符长度
print('hello'.endswith('lo',3))
#True
#判断结束字符是否为lo,默认从下标0开始查找,包含下标0的位置
endswith 判断结束字符
print('我好'.encode())
print('hello'.encode())
# print('hela!~@@~!\xe2lo'.encode('gbk',errors='strict'))
print(b'\xe6\x88\x91\xe5\xa5\xbd'.decode('utf-8'))

#b'\xe6\x88\x91\xe5\xa5\xbd'
#b'hello'
#我好


#将字符串进行编码,最终返回以b开头的编码格式
encode 编码
print('heelloe'.count('e',1,2))
#1
#表示从开始下标1包括下标1位置查找字符e,结束位置为下标2,不包括结束位置
#统计结果为1
count 统计相同的字符
print('aaa'.center(22,'+'))
#+++++++++aaa++++++++++
#表示将字符aaa的位置显示在长度为22的中间位置,默认是空格方式填充,这里以+号填充方便演示效果,注意,由于22-3(字符本身3个长度),剩余的并不能整除,所以先整除的整数部分作为公共的填充内容,剩余的填充到末尾
center 中心显示
print('hDasdd23ellAo'.casefold())
#hdasdd23ellao
 
#将字符串里面所有的字母都转换为小写输出
casefold 字母转换小写
print('hEello World'.capitalize())

#Heello world
#这个方法会将整个字符串的第一个字母大写,其余都是小写输出,如果第一个字符串不是字母,则只将其余字母转换成小写
capitalize 首字母大写

 

 

3.list

#定义一个列表
b = ['a','hello','python','1']
#查看列表的内置方法
dir(b)
# 2.x 输出 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

# 3.x输出['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

b.append('tail')    #在列表末尾追加一个元素'tail'
b.count('python')    #统计列表中有多少个相同的元素'python' 
b.extend('how')    #在列表后面追加三个字符串'h','o','w'
b.index('python')    #显示元素‘python’的索引,这里将输出2
b.insert(1,'niubi')    #在索引为的位置插入元素'niubi',及原来的元素从1往后加1
b.pop()    #将列表最后一个元素删除
b.remove('niubi')    #删除指定元素,即,将指定的'niubi'元素删除
b.reverse()    #将列表的元素由原来的从左到右顺序变成从右到左方式排序
b.sort()    #将列表按照assci🐎顺序排序,注意!3.x版本的排序是不能同时有多个数据类型一起排序的。
b.clear()    #将列表b清空,这个方法只有3.x才有
a = b.copy()    #将列表b复制给a,貌似没有发现有什么其它特别之处相对于直接使用a = b方式,这个属性也是只有3.x版本才有

 

 

 

4.tuple

#例如,定义一个元组
a = ('a','hello','python','1')
#查看元组的内置方法
dir(a)
#将会输出一个列表形式的方法名称
# 2.x  输出['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

#3.x输出 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

#元组提供了两个公有方法给我们使用
a.count('hello')        #统计元组里面有多少个相同的元素'hello',很显然,这里只有1个,所以输出结果为 1

a.index('hello')        #返回元素'hello'的索引位置,python的索引位置是从0开始的,所以这里的‘hello’元素的索引是1,而不是2.


#元组的访问方式
a[1]    #显示下标为1的元素,因为元组的下标是从0开始的,所以会显示元素'hello'
a[2]    #这里会显示第python这个元素
a[0:1]    #显示元素从位置0(包括0)  到1(不包括1),即显示'a'
a[0:2]    #显示元素从位置0(包括0)到2(不包括2),即显示('a','hello')
a[-1]    #显示倒数第一个元素,即'1' 
a[-2]    #显示倒数第二个元素,即'python'
a[:-2]    #显示元素从位置0(包括),到位置倒数第二个(不包括倒数第二个),之前的元素都显示出来,即('a','hello')
a[-2:]    #显示元素从位置倒数第二个(包括)到最后一个(包括),即('python','1')
a[0:4:2]    #该方式先将前面的[0:4]条件先筛选出来,然后再进行后面的:2,即每隔一位取一个值,所以这里将显示('a','python')

 

 

5.dict

#python3.5
dir(dict)
#['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

#python2.x
dir(dict)
#['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
food = {'1':'apple','2':'banana'}
print(food)
food.clear()
print(food)

#{'2': 'banana', '1': 'apple'}  正常打印结果
#{}        调用字典函数clear打印结果
clear 清空字典
food = {'1':'apple','2':'banana'}
newfood = food.copy()
print(newfood)
#{'1': 'apple', '2': 'banana'}  打印输出,
copy 浅拷贝字典
food = {'1':'apple','2':'banana'}
print(food.fromkeys(('w'),('2','5')))
print(food)

#{'w': ('2', '5')}
#{'2': 'banana', '1': 'apple'}

#注意,这个操作并不会改变字典的数据值,仅仅是返回一个新字典
fromkeys 返回一个新字典
food = {'1':'apple','2':'banana'}
print(food.get('22'))
print(food.get('1'))
print(food.get('22','neworange'))
print(food.get('1','neworange'))
print(food)

#None   如果没有这个key将返回一个默认值none
#apple   如果能能查到key则显示对应的值
#neworange  如果查不到,则显示默认的值
#apple    如果能查到key,只显示key对应的值,否则使用默认的值
#{'1': 'apple', '2': 'banana'}   get不会改变字典内容
get 获取字典值
food = {'1':'apple','2':'banana'}
print(food.items())
 
#dict_items([('1', 'apple'), ('2', 'banana')])  将字典的键存放在一个元组,对应的值也放在另一个元组里面,返回
items 获取字典的key,values
food = {'1':'apple','2':'banana'}
print(food.keys())
 
#dict_keys(['2', '1'])
keys 以元组形式返回字典键
food = {'1':'apple','2':'banana'}
result = food.pop('1')
print(result)
print(food)

#apple   将被删除的键对应的值返回
#{'2': 'banana'}   打印更新后的字典
pop 删除指定的键值对
food = {'1':'apple','2':'banana'}
print(food.popitem())
print(food)

#('1', 'apple')   随机删除键值对
#{'2': 'banana'}   返回删除后的字典
popitem 随机删除键值对
food = {'1':'apple','2':'banana'}
print(food.setdefault('3','orange'))
print(food)

#orange  默认的值
#{'3': 'orange', '2': 'banana', '1': 'apple'}   打印字典
setdefault 设置默认的键值对
food = {'1':'apple','2':'banana'}
goods = {'1':'TV','22':'Computer'}
print(food.update(goods))
print(food)


#None
#{'2': 'banana', '1': 'TV', '22': 'Computer'}  如果存在对应的key则更新value,否则新增键值对
update 更新字典
food = {'1':'apple','2':'banana'}
print(food.values())
 

    #dict_values(['apple', 'banana'])
values 以列表形式返回字典的值

 

6.数据类型转换

  列表转换成元祖

#定义一个列表
a = ['a', 'b', 'c']

#通过tuple函数,将列表转换成元组,我们把新生成的元组赋值给c
c = tuple(a)

print(c)
#结果显示('a', 'b', 'c'),说明我们现在已经把列表转换成一个新的元组了。

  元组转换成列表

#由于元组上不可更改的,当我们想变更时该怎么办呢?只能将元组转换成列表,将其修改后,再转换成元祖形式
#定义一个元组
a = ('a','b','c')

#使用list函数将元组转换成列表,然后赋值给一个新的变量名为c,这样c就有list函数所有属性了
c = list(a)
print(c)


#打印结果输出为 ['a', 'b', 'c'],通过这种方法,如果我们想在现有的元组基础上做操作修改,可以先转换成列表,列表是考验直接修改元素的,修改完后,我们再将它转换成元组,重新赋值给a

 

 

 

7.文件处理

  7.1文件操作语法

file object = open(file_name,[access_mode],[buffering])

  ·file_name:file_name参数是一个字符串值,包含要访问的文件的名称。

  ·access_mode:access_mode确定该文件已被打开,即模式。读、写等追加,可能值的一个完整 列表在下表中给出。这是可选的参数,默认文件访问模式是读(r)

  ·buffering:如果缓冲值被设置为0,没有缓冲将发生。如果该缓冲值是1,将在访问一个文件进行缓冲。如果指定的缓冲值作为大于1的证书,那么缓冲操作将被用指定缓冲器大小进行。这是可选的参数。

 

  7.2文件访问模式

模式 描述
r 以只读方式打开文件,文件指针放在文件开头,这个是默认模式
rb 以二进制格式读取,文件指针放在文件开头
r+ 以读取和写入方式打开文件,文件指针在文件开头
rb+ 以二进制读取和写入方式打开文件
w 以只写方式打开文件,如果文件存在,则覆盖文件内容,不存在则创建一个新文件
wb 打开文件以二进制方式写入,文件存在则覆盖,不存在则创建新文件
w+ 以写入和读取方式打开文件,如果文件存在则覆盖,不存在则创建新文件
wb+ 以二进制方式写入和读取文件,存在则覆盖现有文件,不存在则创建新文件
a 以追加方式写入文件末尾,如果不存在则创建该文件
ab 以二进制格式追加在文件末尾,不存在则创建该文件
a+ 以追加和读取方式打开文件,如果文件存在,文件指针在文件的末尾,如果不存在,则创建新文件并写入和读取

 

 

  7.3文件的操作示例

open_file = open('/tmp/file.txt',r+)     #以读取和写入方式打开文件

open_file.write('hello\n')    #写入内容,加上换行符,

open_file.close()        #打开文件后,不做操作需要关闭

#文件操作有以下几种方法
#2.x 方法 ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

#3.x 方法['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

 

posted @ 2017-11-19 22:30  小曺  阅读(641)  评论(0编辑  收藏  举报