python内置对象的类型及其所支持的运算

我们在编程时为什么要使用内置对象类型,以及我们在编程时尽可能使用自定义类型呢还是但凡有可能都去使用内置类型。很显然,对于python而言,内置类型更容易理解,执行上的性能也会更好一些。所以除非内置类型无法提供特殊对象处理时,一般而言都会使用内置类型。
内置类型使得其内置对象程序更容易编写,另外内置类型(内置对象)是扩展组件,内置类型往往比自己定义的类型在执行时拥有更高的效率。


python 对象的相关术语


python是一个强类型的语言。
对象: 身份 、类型、值
身份相当于此对象在内存当中的地址。 id(对象)可以获取对象的地址
类型 (类别) type(对象) 可以获取某对象的类型 一般而言对象的类型决定了它所能构支持的运算和它支持的方法。class 自定义类型 type 内置对象的类型 所以
在叫数据类型时都是同一个意思。
值 各种不同类型下不同形式的数据。
#【注】
class : 自定义类型
type : 内置对象的类型 所以
在叫数据类型时都是同一个意思。
instance: 对象的实例化。

类:数据和方法
数据:变量
方法: 函数

属性:所有的对象都是由类实例而来的,而在类实例化成对象时,可以为类的某些变量赋予值,那么这个类中的可用的变量就称为对象的属性。

对象的身份与类型

两个对象的比较:
1.值比较 对象中的数据是否相同。
2.身份比较 两个变量是否易用的是同一对象,即指向相同的内存地址。
3.类型比较 两个对象的类型是否相同。

Python的核心数据类型

用于表示数据的内置类型

Python的核心数据类型
1.数字 int ,long,float, complex
2.字符:str ,unicode
3.列表 list
4.字典 dict
5.元组 tupe
6.文件 file
7.其它类型 集合(set),frozenset,类类型,None,bool

其它文件类工具:
pipes,fifos,sockets,

python类型操作


类型转换常用的内置函数:
str(),repr()或format(): 可以将非字符串类型的数据转换成字符串数据的类型。
int() :转为整数
float()
list(s) 将字符串s转为列表
tuple(s)将字符串s转换为元组
set(s)将字符串s转换为集合
frozenset(s):将字符串s转换为不可变集合。

chr(s):将整数转换成字符
ord(x) :将字符转换成整数值
hex(x):将整数转换为16进制字符
bin(x) 返回一个整数 int 或者长整数 long int 的二进制表示.
oct(x) 函数将一个整数转换成8进制字符串。

dict(d): 根据指定的键值对来创建字典。d必须是key,value的元组的序列


#str(),repr()或format():  可以将非字符串类型的数据转换成字符串数据的类型。
>>> num1=3.14
>>> type(num1)
<class 'float'>
>>> str(num1)
'3.14'
>>> repr(num1)
'3.14'
>>> type(num1)
<class 'float'>
>>> str1=repr(num1)
>>> type(str1)
<class 'str'>
>>> format(num1)
'3.14'
# list(s)  将字符串s转为列表
>>> str1="xiaopang"
>>> list(str1)
['x', 'i', 'a', 'o', 'p', 'a', 'n', 'g']
>>> str(list(str1))
"['x', 'i', 'a', 'o', 'p', 'a', 'n', 'g']"
#tuple(s)将字符串s转换为元组
>>> tuple(str1)
('x', 'i', 'a', 'o', 'p', 'a', 'n', 'g')#set(s)将字符串s转换为集合
>>> set(str1)
{'i', 'g', 'x', 'n', 'p', 'o', 'a'}
#frozenset(s):将字符串s转换为不可变集合。
>>> str2="xiaopangxiaopangnizhenbang"
>>> x=frozenset(str2)
>>> print(x)
File "<stdin>", line 1print��x��^
SyntaxError: invalid character in identifier
>>> x1=frozenset(str2)
>>> print(x1)
File "<stdin>", line 1print��x1��^
SyntaxError: invalid character in identifier
>>> print(x1)
frozenset({'i', 'g', 'x', 'n', 'p', 'h', 'e', 'z', 'b', 'o', 'a'})
>>> print(x)
frozenset({'i', 'g', 'x', 'n', 'p', 'h', 'e', 'z', 'b', 'o', 'a'})
#dict(d):  根据指定的键值对来创建字典。d必须是key,value的元组的序列
>>> l3=[("a",1),("b",11),("c",45)]
>>> di=dict(l3)
>>> print(di)
{'a': 1, 'b': 11, 'c': 45}
#将字符转换成整数值
>>> ord(str2)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 26 found
>>> str="x"
>>> str1="x"
>>> s=ord(str1)
>>> print(s)
120#chr(s):将整数转换成字符
>>> sx=77
>>> chr(sx)
'M'
>>> sx=7
>>> chr(sx)
'\x07'
>>> num8=3
>>> c2=chr(num8)
>>> print(c2)>>> sx=888888
>>> chr(sx)
'\U000d9038'#hex(x):将整数转换为16进制字符
>>> x=6
>>> str5=hex(x)
>>> print(str5)
0x6
#bin(x)将整数转化成二进制
>>> sr6=bin(x)
>>> print(sr6)
0b110
#oct(x)将整数转化成8进制
>>> st=oct(x)
>>> print(st)
0o6#  数字类型
#python不仅支持普通的数据类型像整数,浮点型,还能够通过常量直接去创建数字和处理它的表达式,#另外python海提供了对高级数字支持的编程,包括像复数  complex,以及无穷精度的整数类型固定精度
#的10进制数,集合,bool型和其它各种数字工具的库。
#Python的数字字面量:布尔型,整数,浮点数,复数;
#布尔类型:  True,   False  首字母大写。
#数字类型是不可变类型。#在数字类型中,有个math库是和数学运算库相关的。>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(4)
2.0
##位移运算符操作>>> num7=2
>>> num7 << 3
16
>>> num7<<2
8
>>> num8=81
>>> num8>>2
20
>>> num8=16
>>> num>>3
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'num' is not defined
>>> num8>>3
2
>>> num8<<3
128[注]:一般正数而言,向左移数字会变大,右移数字会变小。        #   & 按位与:     两个都相同为1或者True .
#   |  按位或:     只要有一个为1或为true  ,结果就为1或True.
#  ^    按位抑或: 只要不同结果为1或者为True.
#   ~   按位取反
>>> 1^0
1
>>> 0^0
0
>>> 0|0
0
>>> 0|1
1
>>> 0&0
0
>>> 1&1
1
>>> 0&1
0
>>> True&True
True
>>> True|False
True
>>> True&False
False
>>> False&False
False
>>> False|False
False
>>> True|True
True
>>> True^True
False
>>> True^False
True
>>> False^False
False
>>> ~101
-102
>>> ~1
-2
>>> ~0
-1
>>> ~-2
1
>>> ~-1
0
>>> ~-102
101
#    x^Y :     x**Y
>>> 1**2
1
>>> 2**2
4
>>> (1-0.01) ** 365
0.025517964452291125
>>> (1+0.01) **365
37.78343433288728

序列类型


序列类型:

1.字符型

a:字符串字面量:把文本放入单引号、双引号或三引号中: 三引号与前两者的区
别就在于可以使跨行定义,另外三引号所引用的字符可以包含
控制符回车 符,可以使用三个单引号或者三个双引号。
‘’’ ‘’’ 或 “”" “”"
[在python2当中,字符串字面两对应于8位字符或面向字节
的数据,因此它们无法完全支持国际字符集unicode,如果要
想使用unicode进行编码的话,我们必须在定义字串之前加
上u来表示]如下图:

[ 在python3中已经支持unicode了。如下图:]

b:文档字串:模块、类或函数的第一条语句是一个字符串的话,该字符串就成
为文档字符串,可以使用__doc__来显示。注意:文档字串在这个
代码块中要有缩进作为整个代码段的语句。

[注].printName这个函数名后面不加()时不是调用函数本身,而是
引用函数对象,函数对象的名称和调用函数是两码事,加上()表
示调用函数,不加()表示引用函数对象,因为函数本身也是作为
内存对象存在内存中的。所以函数名不加括号可以引用__doc__
属性,将字符串文档显示出来。另外文档字符串 是跟整个代码
缩进一致的。

()是调用运算符,只有那些可调用对象才能支持调用运算,但是
可以不调用可调用对象,但是可以引用

###适用于所有序列的操作和方法

运算符:
索引运算:[i]
切片运算符:[i:j] 切片后的结果会生成为新对象.
扩展切片:[i:j:stride]

切片实例:

>>> str1="xiaopanglikesinging"
>>> str[0:]
'hello world'
>>> str1[0]
'x'
#切片
>>> str1[0:6]
'xiaopa'
#按步长切片
>>> str1[0:6:2]
'xap'>>> str1[0:6:-1]
''
#倒着切片
>>> str1[6:0:-1]
'napoai'
>>> len(str1)
19
#按索引获取字符串中的字符
>>> str[18]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> str1[18]
'g'
>>> str1[-1]
'g'
>>> str1[-1:-3]
''
>>> str1[-3:-1]
'in'
>>> str1[-3:]
'ing'
>>> str1[-3::-1]
'ignisekilgnapoaix'

在这里插入代码片
#max()取序列中的最大值   字符的话是按照ascii码的数值进行比较的大小的
>>> max(str1)
'x'
#min()取序列中的最小值
>>> min(str1)
'a'
>>> str3="946123"
>>> max(str3)
'9'
>>> min(str3)
'1'
>>> sum(str3)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> sum(list(str3))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> sum(list(int(str3)))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> sum(int(str3))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
#sum  求数字类型的序列的和
>>> list=[1,2,3,4]
>>> sum(list)
10
>>> list1=[1.111,5.20,3.14]
>>> sum(list1)
9.451
>>> print(str1)
xiaopanglikesinging
#判断序列中是否含有False
>>> all(str1)
True
>>> str3="hellow"
>>> all(str3)
True
#是否是大写
>>> str3.isupper()
False
#字母转大写
>>> str3.upper()
'HELLOW'
>>> str1.isupper()
False
>>> str1.upper()
'XIAOPANGLIKESINGING'
>>> str1.captialize()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'captialize'
>>> str1.captalize()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'captalize'
#字母型字符串的首字母转成大写
>>> str1.capitalize()
'Xiaopanglikesinging'
>>> str1.index("edu")
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: substring not found
#寻找序列中元素的索引
>>> str1.index("pang")
4>>> str1.index("x",0)
0
>>> str1.index("x",1)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: substring not found
#指定索引区间寻找某个元素的下标
>>> str1.index("p",0,10)
4
>>> list1=["xioapang","like","eating" ]
>>> "|"。join(list1)
File "<stdin>", line 1"|"��join(list1)^
SyntaxError: invalid character in identifier
#将序列中的每个元素之间重新设置分隔符
>>> "|".join(list1)
'xioapang|like|eating'
>>> "@".join(str1)
'x@i@a@o@p@a@n@g@l@i@k@e@s@i@n@g@i@n@g'
#转大写  转小写
>>> (str1.upper()).lower()
'xiaopanglikesinging'
>>> str1.replace("singing","xiaohe")
'xiaopanglikexiaohe'
#以某个符号切分成几段,返回一个列表
>>> str1.split("*")
['xiaopanglikesinging']
>>> str1.split("|")
['xiaopanglikesinging']
>>> str1="xiaopang"
>>> str1.split(".")
['xiaopang']
>>> str1.split("o")
['xia', 'pang']
>>> str1="   xiaopang   "
>>> str1.strip()
'xiaopang'
#
>>> help(str.strip)
Help on built-in function strip:strip(...) method of builtins.str instanceS.strip([chars]) -> strReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.#删除字符串的空格或指定元素
>>> str1.strip().strip("g")
'xiaopan'

查看某个类下的所有方法:

列表:

容器类型:
任意对象的有序集合,通过索引访问其中的元素,可变对象,支持异构(任意几种不同类型的数据同时存在),可以任意嵌套。

支持在原处修改:修改了元素对象的引用。
1 修改指定索引的元素
2 修改指定的分片。
3 删除语句,
4 内置方法

列表1+列表2: 合并两个列表,返回一个新的列表;
不会修改原列表
列表 *N :表示把列表重复N次,返回一个新列表;

in:成员关系判断字符。用法:item in container

not in: 成员关系判断字符。用法: item not
incontainer
列表解析:能够使用表达式生成一个列表。
列表的复制方式:
1.潜复制
l1=[1,2,3,4]
l2=l1
2.深复制 (2种方式)
import copy
a: l2=copy.deepcopy(l1)

b: l2=l1[:]

>>> l1=[]
>>> print(l1)
[]
#打印内存地址
>>> id(l1)
50729352
>>> l2=[1,2,3,4,5]
>>> priint(l2)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'priint' is not defined
>>> print(l2)
[1, 2, 3, 4, 5]
>>> l3=[1,"2",(2,1)]
>>> print(l3)
[1, '2', (2, 1)]
>>> l3[1]=32
>>> print(l3)
[1, 32, (2, 1)]
>>> l3[3]="xiaopang"
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> l3[2]="xiaopang"
>>> print(l3)
[1, 32, 'xiaopang']
>>> print(l3[0:1])
[1]
>>> print(l3[0:2])
[1, 32]
>>> print(l3[0:])
[1, 32, 'xiaopang']
>>> l3[-3:-2]="xioazheng"
>>> print(l3)
['x', 'i', 'o', 'a', 'z', 'h', 'e', 'n', 'g', 32, 'xiaopang']
>>> l3[-3:-2]=0
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
>>> l3[-3]=0
>>> print(l3)
['x', 'i', 'o', 'a', 'z', 'h', 'e', 'n', 0, 32, 'xiaopang']
>>> l3[:-2]=[]
>>> print(l3)
[32, 'xiaopang']
#删除列表中的每个元素
>>> del(l3[0])
>>> print(l3)
['xiaopang']
>>> del(l3)
>>> print(l3)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'l3' is not defined
>>> l4=[1,2,3,4,56,8]
>>> l4.append("xiaopang")
>>> print(l4)
[1, 2, 3, 4, 56, 8, 'xiaopang']
>>> id(l3)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'l3' is not defined
>>> id(l4)
50729864
>>> l3=["like","mangguo"]
>>> l4.append(l3)
>>> print(l4)
[1, 2, 3, 4, 56, 8, 'xiaopang', ['like', 'mangguo']]
>>> l4.count(2)
1
#追加
>>> l4.extend(l3)
>>> print(l4)
[1, 2, 3, 4, 56, 8, 'xiaopang', ['like', 'mangguo'], 'like', 'mangguo']
>>> l4.index("xiaopang")
6
#extend追加序列时,会将中的每个元素单独的追加进去
>>> list1=[1,2]
>>> list2=["xiaopang",("like","mangguo"),{"and":"xiaohe"}]
>>> list1.append(list2)
>>> print(list1)
[1, 2, ['xiaopang', ('like', 'mangguo'), {'and': 'xiaohe'}]]
>>> list1.extend(list2)
>>> print(list1)
[1, 2, ['xiaopang', ('like', 'mangguo'), {'and': 'xiaohe'}], 'xiaopang', ('like', 'mangguo'), {'and'
: 'xiaohe'}]>>> list2=["xiaopang",("like","mangguo"),{"and":"xiaohe"},["xiaopang","like","music"]]
>>> list3=[1,2]
>>> list3.extend(list2)
>>> print(list3)
[1, 2, 'xiaopang', ('like', 'mangguo'), {'and': 'xiaohe'}, ['xiaopang', 'like', 'music']]
>>> list2=("xiaopang",("like","mangguo"),{"and":"xiaohe"},["xiaopang","like","music"])
>>> tupe2=list2
>>> list3.extend(tupe2)
>>> print(list3)
[1, 2, 'xiaopang', ('like', 'mangguo'), {'and': 'xiaohe'}, ['xiaopang', 'like', 'music'], 'xiaopang'
, ('like', 'mangguo'), {'and': 'xiaohe'}, ['xiaopang', 'like', 'music']]
>>> dict1={"a":"yellow","b":"red","c":"white"}
>>> list3.extend(dict1)
>>> print(list3)
[1, 2, 'xiaopang', ('like', 'mangguo'), {'and': 'xiaohe'}, ['xiaopang', 'like', 'music'], 'xiaopang'
, ('like', 'mangguo'), {'and': 'xiaohe'}, ['xiaopang', 'like', 'music'], 'a', 'b', 'c']
>>> list1=[1,2]
>>> list1.extend(dict1)
>>> print(list1)
[1, 2, 'a', 'b', 'c']>>>
>>> help(list.insert)
Help on built-in function insert:insert(...) method of builtins.list instanceL.insert(index, object) -- insert object before index>>>
>>> l4.insert(6,""xiaozheng")
File "<stdin>", line 1l4.insert(6,""xiaozheng")^
SyntaxError: invalid syntax
#在指定的索引位置插入某一个元素
>>> l4.insert(6,"xiaozheng")
>>> print(l4)
[1, 2, 3, 4, 56, 8, 'xiaozheng', 'xiaopang', ['like', 'mangguo'], 'like', 'mangguo']
#
#取出并删除列表中指定索引位置的元素,参数必须是一个整数索引,不写默认为取出并删除列表的最后一个元素
>>> l4.pop(0)
1
>>> l4.pop(1)
3
>>> l4.pop()5
File "<stdin>", line 1l4.pop()5^
SyntaxError: invalid syntax
>>> l4.pop(5)
'xiaopang'
>>> l4.pop(5)
['like', 'mangguo']
>>> print(l4)
[2, 4, 56, 8, 'xiaozheng', 'like', 'mangguo']
#删除列表当中的指定的元素     参数为指定的元素
>>> l4.remove(0)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> l4.remove(8)
>>> print(l4)
[2, 4, 56, 'xiaozheng', 'like', 'mangguo']
#将列表中的元素顺序翻转过来
>>> l4.reverse()
>>> print(l4)
['mangguo', 'like', 'xiaozheng', 56, 4, 2]
>>> l4.sort()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>> l3=[1,23,2,67.3,4,23,45,2,32,34]
#排序
>>> l3.sort()
>>> print(l3)
[1, 2, 2, 4, 23, 23, 32, 34, 45, 67.3]>>> l5=[1,2,3]
>>> l6=["x","y","y"]
>>> id(l5)
50786504
>>> id(l6)
50788552
>>> print(l5+l6)
[1, 2, 3, 'x', 'y', 'y']
>>> str1="xiaopang like"
>>> str2="sleep"
#拼接两个字符串
>>> print(str1+str2)
xiaopang likesleep
#将某个字符串重复3次
>>> str1*3
'xiaopang likexiaopang likexiaopang like'
>>> l5*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
#判断某个元素是否存在于序列中
>>> 2 in l5
True
#判断某个元素是否不存在于序列中
>>> "y" not in l6
False>>> l5[2]=["mangguodaxia"]
>>> print(l5)
[1, 2, ['mangguodaxia']]
>>> l5[2]=['xiaopang',"like","mangguo"]
>>> print(l5)
[1, 2, ['xiaopang', 'like', 'mangguo']]
>>> l5.pop(2)
['xiaopang', 'like', 'mangguo']
>>> print(l5)
[1, 2]
>>> l1=["xiaopang",""like","mangguo"]
File "<stdin>", line 1l1=["xiaopang",""like","mangguo"]^
SyntaxError: invalid syntax
>>> l1=["xiaopang","like","mangguo"]
>>> l5.appende(l1)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'a
>>> l5.append(l1)
>>> print(l5)
[1, 2, ['xiaopang', 'like', 'mangguo']]
>>> l5.del(["xiaopang","like","mangguo"])
File "<stdin>", line 1l5.del(["xiaopang","like","mangguo"])^
SyntaxError: invalid syntax
>>> l5.remove(["xiaopang","like","mangguo"])
>>> print(l5)
[1, 2]
>>> l5[1:]=["xiaopang","like","mangguo"]
>>> print(l5)
[1, 'xiaopang', 'like', 'mangguo']
##原教程在python2环境下操作,因此python3下会出现如下情况
>>> range(10)
range(0, 10)
>>> xrange(0,10)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'xrange' is not defined
>>>

pop

range()与xrange()在python2中的效果:
range() 生成一个列表

#潜复制   引用的是同一个内存地址
>>> l7=[1,2,3]
>>> l8=l7
>>> print(l8)
[1, 2, 3]
>>> l7.append(4)
>>> print(l7)
[1, 2, 3, 4]
>>> print(l8)
[1, 2, 3, 4]
>>> id(l7)
50821064
>>> id(l8)
50821064
#  复制了一份数据创建引用了新的内存对象
>>> l9=l7[:]
>>> print(l9)
[1, 2, 3, 4]
>>> id(l9)
50869576>>> import copy
>>> help(copy.deepcopy)
Help on function deepcopy in module copy:deepcopy(x, memo=None, _nil=[])Deep copy operation on arbitrary Python objects.See the module's __doc__ string for more info.
### 深复制的用法
>>> id(l7)
50821064
>>> l10=l7.copy.deepcopy(l7)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'deepcopy'
>>> l10=copy.deepcopy(l7)
>>> id(l10)
49714504

元组(不可变)

表达式符号:()
容器类型
任意对象的有序集合,通过索引访问其中的元素,不可不变对象,长度固定 异构,嵌套

常见操作:
不支持原处修改。
()
(1,)
(1,2)

t1+t2: 拼接两个元组
t1*N : 重复元组t1N次显示

in : obj in container
not in : obj not in container
[注]定义元组时可以省略(),但一般而言仅当元组作为字符传给函数调用以及当元组出现在print语句的特殊情况时,()才是必要的。
虽然元组不可变,但不意味着其真不可变。变化之后不会创建新的对象。
虽然元组本身不可变,但如果元组内部嵌套了可变类型的元素,那么此类元素的修改不会返回新元组。如下图:

>>> t1=(1,2,3,4)
#元组中的元素个数
>>> t1.count(2)
1
#返回元组中某个元素的索引
>>> t1.index(3)
2
>>> 3 in t1
True
>>> "xiaopang" in t3
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 't3' is not defined
>>> "xiaopang" in t1
False
#元组的切片
>>> print(t1[1:])
(2, 3, 4)
>>> t2=()
#元组的长度或者元组中元素的个数
>>> len(t2)
0
>>> t3=(,)
File "<stdin>", line 1t3=(,)^
SyntaxError: invalid syntax
>>> print(t1(1,2))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
>>> print(t1(0,1))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
>>> print(t1[0,1])
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: tuple indices must be integers or slices, not tuple
>>> print(t1[0:1])
(1,)
#定义元组时可以将小括号直接省略掉。
>>> t4="x","y","z"
>>> print(t4)
('x', 'y', 'z')
>>> type(t4)
<class 'tuple'>
>>> print(t1)
(1, 2, 3, 4)
#拼接两个元组
>>> t1+t4
(1, 2, 3, 4, 'x', 'y', 'z')
#重复某个元组数次
>>> t4*3
('x', 'y', 'z', 'x', 'y', 'z', 'x', 'y', 'z')

字典 dict 可变

除了列表之外的最灵活的序列,内置类型。
字典在其它编程语言中又称关联数组或散列表:
通过键实现元素存取: 无序集合:可变类型容器,长度可变,异构,嵌套;
{key1:value1,key1:value2,…}
{}空字典
{“x”:32,“y”:[1,2,3]}
dict.copy()
dict.iteritems()
字典不允许对一个键赋多个值的。另外大多数的python对象都可以用做键,但它们必须是可hash的对象,才能用作键的。因为它的查找方式是把每一个键做成hash表,所以说它的速度比较快。因为字典本身是不可哈希的,所以不能用字典本身当作键,不过字典本身可以用作值的。

#根据字典的键获取字典的值
>>> dict1={"x":"xiaopang","y":["xiaopang","like","eating"]}
>>> print(dict1["x"])
xiaopang
>>> print(dict1["y"][0])
xiaopang
>>> print(dict1["y"][1])
like
>>> print(dict1["y"][2])
eating
>>> print(dict1["y"][0:])
['xiaopang', 'like', 'eating']
#字典中元素的个数或者字典的长度
>>> len(dict1)
2
#清空空字典
>>> dict1.clear()
>>> print(dict1)
{}
#深度复制字典     相当于创建了一个新的对象
>>> dict1={"x":"xiaopang","y":["xiaopang","like","eating"]}
>>> dict2=dict1.copy()
>>> print(dict2)
{'x': 'xiaopang', 'y': ['xiaopang', 'like', 'eating']}
>>> id(dict1)
47705472
>>> id(dict2)
49643456
>>> d3=d1
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'd1' is not defined
#赋值对象    潜复制
>>> dict3=dict1
>>> id(dict3)
47705472
#获取字典中所有的键
>>> dict1.keys()
dict_keys(['x', 'y'])
>>> help(dict.items)
Help on method_descriptor:items(...)D.items() -> a set-like object providing a view on D's items
#将字典转换为元组
>>> dict1.items()
dict_items([('x', 'xiaopang'), ('y', ['xiaopang', 'like', 'eating'])])
>>> print(dict1.items())
dict_items([('x', 'xiaopang'), ('y', ['xiaopang', 'like', 'eating'])])
#解包 支持元组,列表
>>> t1,t2=dict1.items()
>>> print(t1)
('x', 'xiaopang')
>>> print(t2)
('y', ['xiaopang', 'like', 'eating'])
>>> t1,t2,t3=dict1.items()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)#更新合并字典,会覆盖掉间相同的原来的值
>>> dict1={'y': ['xiaopang', 'like', 'eating'],"b":"red","c":"yellow","d":23,"e":666}
>>> dict2={"y":["xiaopang","like","xiaohe"],"b":"Chinese"}
>>> dict1.update(dict2)
>>> print(dict1)
{'y': ['xiaopang', 'like', 'xiaohe'], 'b': 'Chinese', 'c': 'yellow', 'd': 23, 'e': 666}
>>> print(dict2)
{'y': ['xiaopang', 'like', 'xiaohe'], 'b': 'Chinese'}

python2中:

dict中的方法:

#dict.iteritems() 用于返回迭代器对象
d1={“y”:44,""x:1,“m”:21,“n”:76},

xrange()生成的对象不能够使用next()方法



dict()定义字典

#viewitems() 利用集合的 方式显示字典的键。
#viewvalues() 利用集合的方式显示字典中所有的值。

zip

help(zip)

zip(“a”,“b”,“c”)
python3:
pytjhon3中zip()仅支持两个参数。


#转成list
######## zip(中两个的参数的元素个数不一致时,一一配对,会省略掉多余的元素)

python2:


可以使用zip构造字典: 用来实现将列表快速构建字典的方时式

序列支持的操作符


后续的对象类型将在后面的博客中继续更新。

完结 感谢观看

python对象类型及其运算 数字 字符串 list dict tupe dict相关推荐

  1. python布尔类型运算_Python对象类型及其运算方法(详解)

    基本要点: 程序中储存的所有数据都是对象(可变对象:值可以修改 不可变对象:值不可修改) 每个对象都有一个身份.一个类型.一个值 例: >>> a1 = 'abc' >> ...

  2. Python对象类型及相关操作

    文章目录 Python对象类型 对象操作函数 1.数字类型 常用的算术运算符: 数字运算相关的内置函数: math模块中的常用函数: 2.字符串 1.字符编码 2.字符串表示 3.转义字符串 4.字符 ...

  3. python 对象类型有哪些?

    python 强大的内置类型让我接触到python的时候开始慢慢的喜欢上它了,感觉既方便又好用,下面我们先一起学习下内置对象类型的好处: 1内置对象能够使得我们编写程序更容易. 2内置的对象效率更高, ...

  4. Python对象类型

    Python对象类型 Python进阶(二)--Python对象类型 上一章中我们主要讲了Python的安装与Python基本命令行,IDLE的应用.本章中我们将讲述Python的对象类型,包括数字. ...

  5. python中一切内容都可以称为对象吗_python对象类型及其运算2

    python一切皆对象,所有内容都是由对象展开的,对象是由类实例化而来. python中存储的所有数据都是对象. 每个对象都有一个身份.一个类型和一个值. 身份:eg:school="bei ...

  6. Python对象类型——字符串、列表、元组

    字符串 Python连接多个字符串可用"+"号,但这个操作不如把所有子字符串放到一个列表或可迭代对象中,然后调用一个join方法来把所有内容连接在一起节约内存. 原始字符串操作符( ...

  7. python数字类型及运算_Python类型和运算--数字

    在Python中,数字并不是一个真正的对象类型,而是一组相似类型的分类.不仅包括通常的数字类型(整数和浮点数),黑包括数字表达式,以及高级的数字编程. 基本数字常量 数字 常量 1234, -24 整 ...

  8. 第4章 介绍Python对象类型

    看前须知 这里对本书中提到的不常见的内容进行了查证,举例,所以大家可以不用再费神去搜索相关内容 在Python中,我们运用"材料"来处理"事务". 材料:操作对 ...

  9. 少儿编程100讲轻松学python(四)-python如何判断是否为数字字符串

    前言 python判断是否为数字字符串的方法: 1.通过创建自定义函数[is_number()]方法来判断字符串是否为数字: 2.可以使用内嵌if语句来实现. python判断是否为数字字符串的方法: ...

最新文章

  1. iOS使用自签名证书实现HTTPS请求
  2. Angular搭建框架比较好用的插件
  3. 史上最全的Linux常用——目录和文件管理命令——收藏这一篇就够了!(超全,超详细)
  4. classpath环境变量
  5. 数字信号处理2:傅里叶变换
  6. Lucene全文检索_分词_复杂搜索_中文分词器
  7. 基于统计的压缩算法:游程编码
  8. 技巧:MacOS 中快速复制文件或文件夹路径
  9. 英国大学diploma(证书)期末考试挂科
  10. xxl-job 原理:
  11. JAVA查询银行卡信息
  12. html 恶意广告,电脑自动弹出恶意广告怎么处理
  13. ffmpeg给视频画边框
  14. 应用案例 | 2009 款北京现代伊兰特车换挡冲击故障诊断
  15. API接口之JWT设置token过期时间(二)
  16. 美国商务签证面试经历
  17. ETC营销数据统计及展示
  18. BTC是圈外人(机构)的盛宴,DeFi则是圈内人的狂欢
  19. 月饼大战白热化,保险公司也来Battle了!
  20. 战略与领导力,Sony为何总是顾此失彼?

热门文章

  1. 我的毕业季:从开始工作到大学毕业
  2. 华为鸿蒙os用时间长了会卡吗,外媒再放狠话!华为鸿蒙OS系统和安卓没区别:同样也会越用越卡顿...
  3. PAT乙级题目合集(思路笔记)
  4. SourceTree Clone非常慢原因
  5. python Matplotlib 绘制多个子图
  6. 【C++从入门到放弃】C++编译生成动态链接库*.so及如何调用*.so
  7. SNA(社会网络分析)——三种中心度总结
  8. 黑白图片怎样上色?教你如何给黑白照片上色
  9. NUIST OJ 1350-1352 面朝大海,春暖花开【初识线段树】
  10. 我和python的第一次亲密接触