python基本对象类型

版权声明:所有内容仅供大家学习与复习使用,请勿用于任何商业用途;维特根斯坦曾说过,凡可说的,皆无意义。凡有意义的,皆不得不以荒唐的语言传递其意义。我十分赞同。 https://blog.csdn.net/qq_40828914/article/details/86628099

python对象类型

1.数字

例子

>>> 123+222
345
>>> 1.5*399
598.5
>>> 2**10
1024
>>> 3.1415*2
6.283
>>> 9.9999+1
10.9999
>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(80)
8.94427190999916
>>> import random
>>> random.random()
0.3359936409813997
>>> random.choice([1,2,3,4])
1
>>> random.choice([5,2,3,4])
4

可以看出:

1.python支持一般的数学运算

2.还可以导入一些数学模块,比如math,random模块。

2.字符串

>>> S='span'
>>> len(S)
4
>>> S[0]
's'
>>> S[1]
'p'
>>> S[-1]
'n'
>>> S[-2]
'a'
>>> S[len(S)-1]
'n'
>>> S[1:3]
'pa'
>>> S[1:]
'pan'
>>> S[:-1]
'spa'
>>> S[:0]
''
>>> S[0:]
'span'
>>> S[:]
'span'
>>> S
'span'
>>> S+'xyz'
'spanxyz'
>>> S*8
'spanspanspanspanspanspanspanspan'
>>> S[0]='z'
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    S[0]='z'
TypeError: 'str' object does not support item assignment
>>> S='z'+S[1:]
>>> S
'zpan'
>>> S.find('pa')
1
>>> S.replace('pa','xyz')
'zxyzn'
>>> S
'zpan'
>>> line='aaa,bbb,ccc,ddd'
>>> line.split(',')
['aaa', 'bbb', 'ccc', 'ddd']
>>> S='jymmm'
>>> S.upper()
'JYMMM'
>>> S.isalpha()
True
>>> line
'aaa,bbb,ccc,ddd'
>>> line=line+'\n'
>>> line
'aaa,bbb,ccc,ddd\n'
>>> line='aaa,bbb,ccc,ddd\n'
>>> line
'aaa,bbb,ccc,ddd\n'
>>> line=line.rstrip()
>>> line
'aaa,bbb,ccc,ddd'
>>> '%s,eggs,and%s'%('span','sjdi!')
'span,eggs,andsjdi!'
>>> '{0},eggs,and {1}'.format('spann','isjdi')
'spann,eggs,and isjdi'
>>> S='A\nB\tC'
>>> len(S)
5
>>> ord('S')
83
>>> import re
>>> match = re.match('Hello[ \t]*(.*)world','Hello    Python world')
>>> match.group(1)
'Python '
>>> match=re.match('/(.*)/(.*)/(.*)','/usr/home/jdsis')
>>> match.groups()
('usr', 'home', 'jdsis')
>>> dir(S)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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']
>>> help(S.replace)
Help on built-in function replace:

replace(...) method of builtins.str instance
    S.replace(old, new[, count]) -> str
    
    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.


可以看出:

1.对于字符串来说,他本身就是一个序列,所谓序列就类似于数组,一个包含其他对象的有序集合。因此他是有位置顺序的。那么我们就可以像数组一样对字符串进行操作。

2.对于索引来说,我们可以正向索引,也可以反向索引,正向的话就是和数组一样,下标从零开始,零对应的是第一个元素。而反向的话,则是从-1开始,-1对应了最后一个元素。

3.序列也支持分片操作,S[1:3]意思就是取出字符串的[1,3)下标,也就是下标1和下标2。如果[:]两边有一个是没写数,那么说明是从头开始或者是到结尾结束。

4.序列也支持用数学符号进行合并

5.从例子中我们发现,字符串具有不可变形,就是说你无论怎么对原始字符串进行操作,最终原始字符串都不会发生改变。所以为了改变原始字符串,我们通常需要建立一个新的字符串,并以同一变量名对其赋值。

6.字符串也具有一些操作方法,比如find,replace,upper,isalpha等等

7.我们也可以对字符串对象进行模式匹配

8.寻求帮助:dir和help,dir返回一个列表,其中包含了对象的所有属性,包括方法名称,然后我们用help查询方法就可以知道他是做什么怎么用的

3.列表

>>> L=[123,'spsdis',1.232]
>>> len(L)
3
>>> L[0]
123
>>> L[:-1]
[123, 'spsdis']
>>> L+[4,5,6]
[123, 'spsdis', 1.232, 4, 5, 6]
>>> L
[123, 'spsdis', 1.232]
>>> L.append('NNI')
>>> L
[123, 'spsdis', 1.232, 'NNI']
>>> L.pop(2)
1.232
>>> L
[123, 'spsdis', 'NNI']
>>> M=['ss','sssd','sff']
>>> M.sort()
>>> M
['sff', 'ss', 'sssd']
>>> M.reverse()
>>> M
['sssd', 'ss', 'sff']
>>> L[99]
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    L[99]
IndexError: list index out of range
>>> L[99]=1
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in <module>
    L[99]=1
IndexError: list assignment index out of range
>>> M=[[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> M[1]
[4, 5, 6]
>>> M[1][2]
6
>>> col2=[row[1] for row in M]
>>> col2
[2, 5, 8]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[1]+1 for row in M]
[3, 6, 9]
>>> [row[1] for row in M if row[1]%2==0]
[2, 8]
>>> diag=[M[i][i]for i in [0,1,2]]
>>> diag
[1, 5, 9]
>>> S
'A\nB\tC'
>>> doubles=[c*2 for c in 'djfijsi']
>>> doubles
['dd', 'jj', 'ff', 'ii', 'jj', 'ss', 'ii']
>>> G=(sum(row) for row in M)
>>> next(G)
6
>>> next(G)
15
>>> list(map(sum,M))
[6, 15, 24]
>>> {sum(row) for row in M}
{24, 6, 15}
>>> {i:sum(M[i]) for i in range(3)}
{0: 6, 1: 15, 2: 24}
>>> [ord(x) for x in 'sdffs']
[115, 100, 102, 102, 115]
>>> {ord(x) for x in 'sdffs'}
{115, 100, 102}
>>> {x:ord(x) for x in 'sdffs'}
{'s': 115, 'd': 100, 'f': 102}

可以看出:

1.列表是一个任意类型的对象的位置相关的有序集合,其大小可变

2.能够对列表进行索引,切片,合并等操作,但是这样不会对原列表修改

3.还具有其列表类型特定的操作,append,pop,这里是可以直接对列表进行增加或缩减。还有sort,按从小到大顺序对列表进行排序,reverse,翻转字符串

4.尽管列表没有固定大小,但是python不能引用不存在的元素,对列表末尾范围之外进行索引或赋值会报错

5.支持任意类型的嵌套,一个嵌套列表的列表能实现二维矩阵

6.列表解析:通过对序列中的每一项运行一个表达式来创建一个新列表。可以加上if语句进行判断,或是再前面变量进行不同的操作。列表,集合和字典都可用解析来创建

4.字典

>>> D={'food':'nuddle','quantity':4,'color':'pink'}
>>> D['food']
'nuddle'
>>> D['quantity']+=1
>>> D
{'food': 'nuddle', 'quantity': 5, 'color': 'pink'}
>>> D={}
>>> D['name']='BOb'
>>> D['job']='dev'
>>> D['age']=40
>>> D
{'name': 'BOb', 'job': 'dev', 'age': 40}
>>> print(D['name'])
BOb
>>> rec={'name':{'first':'bob','last':'smith'},'job':['dev','mgr'],'age':40.5}
>>> rec['name']
{'first': 'bob', 'last': 'smith'}
>>> rec['name']['last']
'smith'
>>> rec['job']
['dev', 'mgr']
>>> rec['job'][-1]
'mgr'
>>> rec['job'].append('ds')
>>> rec
{'name': {'first': 'bob', 'last': 'smith'}, 'job': ['dev', 'mgr', 'ds'], 'age': 40.5}
>>> rec=0
>>> D={'a':1,'b':2,'c':3}
>>> D
{'a': 1, 'b': 2, 'c': 3}
>>> ks=list(D.keys())
>>> ks
['a', 'b', 'c']
>>> ks.sort()
>>> ks
['a', 'b', 'c']
>>> for key in ks:
	print(key,'=>',D[key])

	
a => 1
b => 2
c => 3
>>> D
{'a': 1, 'b': 2, 'c': 3}
>>> for key in sorted(D):
	print(key,'=>',D[key])

	
a => 1
b => 2
c => 3
>>> for c in 'dddssfg':
	print(c.upper())

	
D
D
D
S
S
F
G
>>> x=4
>>> while x >0:
	print('sdpd!'*x)
	x-=1

	
sdpd!sdpd!sdpd!sdpd!
sdpd!sdpd!sdpd!
sdpd!sdpd!
sdpd!
>>> squares = []
>>> for x in [1,2,3,4,5]:
	squares.append(x ** 2)

	
>>> squares
[1, 4, 9, 16, 25]
>>> squares = [x**2 for x in [1,2,3,4,5]]
>>> squares
[1, 4, 9, 16, 25]
>>> D
{'a': 1, 'b': 2, 'c': 3}
>>> D['e']=99
>>> D
{'a': 1, 'b': 2, 'c': 3, 'e': 99}
>>> D['f']
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    D['f']
KeyError: 'f'
>>> 'f' in D
False
>>> if not 'f' in D:
	print('missing')

	
missing
>>> value = D.get('x',0)
>>> value
0
>>> value = D.get('a',0)
>>> value
1
>>> value = D['x'] if 'x' in D else 0
>>> value
0

可以看出:

1.字典不是序列,而是一种映射。映射是通过键而不是相对位置来存储值。没有可靠的从左至右的顺序,简单地将键映射到值。映射是一个对象集合,它具有可变性,可随需求增大或减小。

2.可以通过键来对字典索引,读取或改变键对应的值和序列类似,但方括号里面的是键而不是下标

3.字典的值能使用字典或链表作为嵌套。可以通过append扩展嵌入的列表。嵌套允许直接并轻松的建立复杂的信息结构。

4.python在最后一次引用对象后(比如赋值),这个对象占用的内存空间将会自动清理掉。

5.由于字典没有固定顺序,所以当我们想要强调键的顺序时,可以通过字典的keys方法收集一个键的列表,用列表的sort方法排序,然后用for循环输出。也可以用sorted内置函数

6.for循环可用在序列对象或字符串中,还有while循环,不仅限于遍历序列

7.迭代协议:一个在迭代操作情况下每次产生一个元素的对象。从左到右扫描一个对象的每个python工具都使用迭代协议。如果说一个对象在进行下一次循环之前先经过一次内置函数的作用,那么这就类似于解析表达式

8.获取不存在的键值会出错,因此为了避免错误的发生,我们可以通过if进行测试,in关系式允许我们查询字典中一个键是否存在。还有其他的方法,比如get方法,有一个默认的值,如果不存在那个键,就输出这个默认值。

5.元组

>>> T=(1,2,3,4,5)
>>> len(T)
5
>>> T+(5,6)
(1, 2, 3, 4, 5, 5, 6)
>>> T
(1, 2, 3, 4, 5)
>>> T[0]
1
>>> T.index(4)
3
>>> T.count(4)
1
>>> T[0]=2
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    T[0]=2
TypeError: 'tuple' object does not support item assignment
>>> T=('shfhf',222,[111,1,123])
>>> T[1]
222
>>> T[2][1]
1
>>> T.append(4)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    T.append(4)
AttributeError: 'tuple' object has no attribute 'append'

可以看出:

1.元组:不可改变的列表,编写在圆括号中,支持任意类型,任意嵌套

2.元组的专有方法:index(a),查看a出现的下标,count(a),查看a出现的次数

3.不能通过append增长或缩短,因为它时不可变的

4.在程序中以列表的形式传递一个对象的集合,它可能随时改变,但元组不会。因此我们有时会使用元组

6.文件

f = open('tt.txt','w')
>>> f.write('hello\n')
6
>>> f.write('world\n')
6
>>> f.close()
>>> f=open('tt.txt')
>>> text=f.read()
>>> text
'hello\nworld\n'
>>> print(text)
hello
world

>>> text.split()
['hello', 'world']
>>> dir(f)
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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']
>>> help(f.seek)
Help on built-in function seek:

seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
    Change stream position.
    
    Change the stream position to the given byte offset. The offset is
    interpreted relative to the position indicated by whence.  Values
    for whence are:
    
    * 0 -- start of stream (the default); offset should be zero or positive
    * 1 -- current stream position; offset may be negative
    * 2 -- end of stream; offset is usually negative
    
    Return the new absolute position.

可以看出:

1.文件对象时python对电脑外部文件的主要接口,要创建一个文件对象,需调用内置的open函数以字符串形式传给文件一个文件名和处理模式的字符串。文件对象提供了多种读和写的方法。

7.其他核心类型

>>> X=set('sshuds')
>>> Y={'h','d'}
>>> X,Y
({'u', 'd', 'h', 's'}, {'d', 'h'})
>>> X&Y
{'d', 'h'}
>>> X|Y
{'h', 'u', 'd', 's'}
>>> X-Y
{'u', 's'}
>>> {x**2 for x in [1,2,3,4]}
{16, 1, 4, 9}
>>> 1/3
0.3333333333333333
>>> (2/3)+(1/2)
1.1666666666666665
>>> import decimal
>>> d=decimal.Decimal('3.14')
>>> d+1
Decimal('4.14')
>>> decimal.getcontext().prec = 2
>>> decimal.Decimal('1.00')/decimal.Decimal('3.00')
Decimal('0.33')
>>> from fractions import Fraction
>>> f=Fraction(2,3)
>>> f+1
Fraction(5, 3)
>>> f+Fraction(1,2)
Fraction(7, 6)
>>> 1>2,1<2
(False, True)
>>> bool('dff')
True

可以看出:

1.其他类型有:集合。集合是唯一的,不可变的对象的无序集合。可以通过内置函数set创建,也可以通过集合常量和表达式创建。集合支持一般数学集合操作

2.固定精度浮点数类型:decimal。分数类型:fraction。布尔值类型

猜你喜欢

转载自blog.csdn.net/qq_40828914/article/details/86628099
今日推荐