Python的六种内置对象
对象的简单理解
>>> a=3
>>> a
3
>>> b=6
>>> b
6
>>> a,b=b,a
>>> a
6
>>> b
3
在python中,a b称为变量,3 6称为对象
a = 3表示变量a引用了对象3, 变量a不能单独存在,必须引用对象
在python中,a,b=b,a变量可以交换
1、整数和浮点数
内置函数id()可以用来得到每个对象在计算机中的内存地址
>>> help(id)
Help on built-in function id in module builtins:
id(obj, /)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
>>> type(2)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> float(3)
3.0
>>> id(3)
2228315515248
>>> id(3.0)
2228322125904
python中整数运算不会溢出,而浮点数会溢出
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
>>> math.pi
3.141592653589793
>>> math.pow(2,3)
8.0
>>> help(math.pow)
Help on built-in function pow in module math:
pow(x, y, /)
Return x**y (x to the power of y).
>>> 2**3
8
>>> 2**1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
>>> 2**10000*0.1
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
2**10000*0.1
OverflowError: int too large to convert to float
print('The result is: ', round(force, 2), 'N')//字符串的拼接
2、字符和字符串
字符串是一种有序排列的对象,称为序列
其他对象类型也是序列,所有的序列都具有以下几种操作:
2.1、连接(加+和乘*)
>>> m = "python"
>>> n = "book"
>>> m+n
'pythonbook'
>>> m*3
'pythonpythonpython'
2.2、测量长度len()
>>> len(m)
6
>>> name = "小春"
>>> len(name)
2
len(obj, /)
Return the number of items in a container.
Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节,
len()返回的是一个对象中包含的“东西”(字符)的个数,并非对象在内存中所占大小(字节)。
2.3、判断元素是否在序列中in
>>> m
'python'
>>> 'p' in m
True
>>> 'm' in m
False
2.4、索引
从左往右:从0开始编号 如 0 1 2 3 4 5
从右往左:从-1开始编号 如 -1 -2 -3 -4 -5
>>> r = "python book"
>>> len(r)
11
>>> r[5]
'n'
>>> r[-6]
'n'
2.5、切片
(在原来的字符串基础上,依据给定范围新建字符串) 字符串[起始:结束:步长]
步长为正表示从左向右展开切片,步长为负表示从右向左展开切片
>>> r[1:9]
'ython bo'
>>> r[1:9:1]
'ython bo'
>>> r[:9:2]
'pto o'
>>> r[2:]
'thon book'
>>> r[:]
'python book'
>>> r[::-1]
'koob nohtyp'
>>> r[-10:8:2]
'yhnb'
>>> r[8:-10:-2]
'o ot'
2.6、内置函数input和print
>>> name = input("your name is:")
your name is:winner
>>> name
'winner'
>>> type(name)
<class 'str'>
>>> print(name)
winner
input所获取的都是字符串,输入12,是字符串12,而非整数12
name = input("your name: ")
age = input("your age: ")
after = int(age) + 10
print("your name is: ", name)
print("after ten years, you are ", after)
2.7、字符串的常用属性和方法
index(...)
S.index(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
>>> s = "python lesson"
>>> s
'python lesson'
>>> s.index('n')
5
>>>
>>> s.index('n',6)
12
>>> s.index('on')
4
split和join
>>> a = "I LOVE PYTHON"
>>> a.split(" ")
['I', 'LOVE', 'PYTHON']
>>> lst = a.split(" ")
>>> lst
['I', 'LOVE', 'PYTHON']
>>> "+".join(lst)
'I+LOVE+PYTHON'
format 字符串的格式化输出
^表示居中,>表示右对齐
>>> "I like {0} and {1}".format("python","money")
'I like python and money'
>>> "I like {0:^10} and {1:>15}".format("python","money")
'I like python and money'
数字在格式化输出中默认是右对齐,4d表示4位整数,.1f表示保留一位小数的浮点数
>>> "She is {0:4d} years old and {1:.1f}m in height".format(28,1.68)
'She is 28 years old and 1.7m in height'
使用dir()函数可以查看每个对象的属性和方法
使用help()函数可以查看对象方法的文档
调用对象的方法的格式为 对象.方法
3、列表[]
(列表是个筐,什么都能装),列表中的元素可以是python中的各种类型的对象
列表即是序列,又是容器
3.1创建列表
>>> a_lst = [2, 3, 3.14, "python lesson", []]
>>> b_lst = [3, 2, 3.14, "python lesson", []]
>>> id(a_lst)
2757014041600
>>> id(b_lst)
2757014186688
列表中的元素是有顺序的,可重复的,列表也是序列,索引和切片操作与字符串相同
>>> lst = ['a', 'b', 'c', 'd']
>>> lst[0]
'a'
>>> s = 'book'
>>> s[0]
'b'
>>> lst[-1]
'd'
>>> lst[1:3]
['b', 'c']
>>> lst
['a', 'b', 'c', 'd']
>>> lst[:3]
['a', 'b', 'c']
>>> lst[::-1]
['d', 'c', 'b', 'a']
>>> lst[::2]
['a', 'c']
列表和字符串的不同点:列表可以根据索引修改,而字符串不可以
>>> lst[1] = 100
>>> lst
['a', 100, 'c', 'd']
>>> s
'book'
>>> s[1] = "p"
Traceback (most recent call last):
File "<pyshell#89>", line 1, in <module>
s[1] = "p"
TypeError: 'str' object does not support item assignment
3.2列表的 + * len() in 操作
因为列表和字符串一样是序列的一种,所以序列的基本操作也都可以适用于列表
>>> lst2 = [1,2,3]
>>> lst
['a', 100, 'c', 'd']
>>> lst + lst2
['a', 100, 'c', 'd', 1, 2, 3]
>>> lst*2
['a', 100, 'c', 'd', 'a', 100, 'c', 'd']
>>> len(lst)
4
>>> "a" in lst
True
>>> 1 in lst
False
3.3、列表的方法
列表是可修改的,但是不可以直接增加元素
>>> lst = [1,2,3,4]
>>> lst[2] = 300
>>> lst
[1, 2, 300, 4]
>>> lst
[1, 2, 300, 4]
>>> lst[4] = 999
Traceback (most recent call last):
File "<pyshell#100>", line 1, in <module>
lst[4] = 999
IndexError: list assignment index out of range
列表追加元素(追加元素后列表在内存中的地址不变,列表的地址自创建起就确定了)
append(object, /) method of builtins.list instance
Append object to the end of the list.
>>> lst
[1, 2, 300, 4]
>>> lst.append("python")
>>> lst
[1, 2, 300, 4, 'python']
insert(index, object, /) method of builtins.list instance
Insert object before index.
>>> lst.insert(0,10)
>>> lst
[10, 1, 2, 300, 4, 'python']
extend(iterable, /) method of builtins.list instance
Extend list by appending elements from the iterable.
>>> lst2 = ['a','b']
>>> lst
[10, 1, 2, 300, 4, 'python']
>>> lst.extend(lst2)
>>> lst
[10, 1, 2, 300, 4, 'python', 'a', 'b']
>>> lst.extend('book')
>>> lst
[10, 1, 2, 300, 4, 'python', 'a', 'b', 'b', 'o', 'o', 'k']
列表删除元素
pop(index=-1, /) method of builtins.list instance
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
>>> lst
[10, 1, 2, 300, 4, 'python', 'a', 'b', 'b', 'o', 'o', 'k']
>>> lst.pop()
'k'
>>> lst
[10, 1, 2, 300, 4, 'python', 'a', 'b', 'b', 'o', 'o']
>>> lst.pop(0)
10
remove(value, /) method of builtins.list instance
Remove first occurrence of value.
Raises ValueError if the value is not present.
>>> lst.remove('b')
>>> lst
[1, 2, 300, 4, 'python', 'a', 'b', 'o', 'o']
clear() method of builtins.list instance
Remove all items from list.
>>> lst2
['a', 'b']
>>> lst2.clear()
>>> lst2
[]
列表排序
sort(*, key=None, reverse=False) method of builtins.list instance
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
>>> lst2 = [2,4,6,1,9,2]
>>> lst2.sort()
>>> lst2
[1, 2, 2, 4, 6, 9]
>>> lst2.sort(reverse = True)
>>> lst2
[9, 6, 4, 2, 2, 1]
reverse() method of builtins.list instance
Reverse *IN PLACE*.
>>> lst2
[1, 2, 2, 4, 6, 9]
>>> lst2.reverse()
>>> lst2
[9, 6, 4, 2, 2, 1]
使用内置函数sorted()对lst2进行排序会返回一个新的列表,并不会对lst2产生影响
>>> lst2
[1, 2, 2, 4, 6, 9, 3]
>>> sorted(lst2)
[1, 2, 2, 3, 4, 6, 9]
>>> lst2
[1, 2, 2, 4, 6, 9, 3]
内置函数reversed()也是返回一个新的列表
>>> reversed(lst2)
<list_reverseiterator object at 0x00000281EADBE910>
>>> list(reversed(lst2))
[3, 9, 6, 4, 2, 2, 1]
>>> lst2
[1, 2, 2, 4, 6, 9, 3]
比较列表与字符串
-
都是序列
-
列表是容器类对象,列表可变
-
字符串不可变
列表和字符串的相互转换
>>> s = "python"
>>> lst = list(s)
>>> lst
['p', 'y', 't', 'h', 'o', 'n']
>>> "".join(lst)
'python'
>>> str(lst)
"['p', 'y', 't', 'h', 'o', 'n']"
4、元组()
可以包含任何类型的对象,用逗号隔开
4.1创建元组
只有一个元素的元组时,需要加一个逗号,否则所以创建就非元组
元组也是序列,有index方法
>>> t = (1,2,"python",[1,2,3])
>>> type(t)
<class 'tuple'>
>>> tuple()
()
>>> tuple([1,23,44])
(1, 23, 44)
>>> ('a',)
('a',)
>>> t = ('a')
>>> t
'a'
>>> [1]
[1]
>>> [1,]
[1]
>>> t = (1,2,"python",[1,2,3])
>>> t.index(2)
1
>>> t[::-1]
([1, 2, 3], 'python', 2, 1)
元组和列表的一个重大区别:元组是不可变对象,不可以修改
4.2修改元组
若要修改元组中的元素,可以将元组先变成列表,改变元素,然后再将列表变回元组
>>> lst = list(t)
>>> lst
[1, 2, 'python', [1, 2, 3]]
>>> lst[1] = 200
>>> lst
[1, 200, 'python', [1, 2, 3]]
>>> t = tuple(lst)
>>> t
(1, 200, 'python', [1, 2, 3])
4.3元组的+ * in操作
>>> t1 = (1,2,3)
>>> t2 = ('a','b','c')
>>> t1 + t2
(1, 2, 3, 'a', 'b', 'c')
>>> t1 * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> len(t1)
3
>>> 1 in t1
True
4.4比较元组和列表
- 元组不可变
- 元组运算速度快
- 两者都是容器类、序列类对象
5、字典 {}
键:值 key:value
5.1创建字典
- key不可重复,value可以重复
- key必须是不可变对象(列表是可变对象,不可作为key),value可以是任何类型的对象,
>>> d={}
>>> type(d)
<class 'dict'>
>>> d = {'name':'winner','age':18,'city':'hangzhou'}
>>> d
{'name': 'winner', 'age': 18, 'city': 'hangzhou'}
>>> dict(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
5.2获取、改变、删除字典中的键值对
获取字典中的值、改变字典中的值、删除字典中的键值对。字典是可变对象
>>> d
{'name': 'winner', 'age': 18, 'city': 'hangzhou'}
>>> d['name']
'winner'
>>> len(d)
3
>>> d['age'] = 17
>>> d
{'name': 'winner', 'age': 17, 'city': 'hangzhou'}
>>> del d['city']
>>> d
{'name': 'winner', 'age': 17}
5.3 in操作
检查某一值是否是字典中键值对的键
>>> d
{'name': 'winner', 'age': 17}
>>> 'age' in d
True
5.4根据字典中的key读取value的方法
>>> help(d.get)
Help on built-in function get:
get(key, default=None, /) method of builtins.dict instance
Return the value for key if key is in the dictionary, else default.
>>> help(d.setdefault)
Help on built-in function setdefault:
setdefault(key, default=None, /) method of builtins.dict instance
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
>>> d = dict([('a',1),('lang','python')])
>>> d
{'a': 1, 'lang': 'python'}
>>> d.get('a')
1
>>> d.get('b')
>>> d.get('b','winner')
'winner'
>>> d.setdefault('b')
>>> d
{'a': 1, 'lang': 'python', 'b': None}
>>> d.setdefault('name','winner')
'winner'
>>> d
{'a': 1, 'lang': 'python', 'b': None, 'name': 'winner'}
5.5字典中增加键值对
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'winner'}
>>> d.update([('price',3.14),('color','white')])
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'winner', 'price': 3.14, 'color': 'white'}
>>> d1 = {'city':'hangzhou'}
>>> d.update(d1)
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'winner', 'price': 3.14, 'color': 'white', 'city': 'hangzhou'}
5.6字典中删除键值对
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'winner', 'price': 3.14, 'color': 'white', 'city': 'hangzhou'}
>>> del d['a']
>>> d
{'lang': 'python', 'b': 'hello', 'name': 'winner', 'price': 3.14, 'color': 'white', 'city': 'hangzhou'}
>>> d.pop('lang')
'python'
>>> d.pop('lang','pascal') //若要求删除的key不存在,为了防止报错,可以返回指定内容pascal
'pascal'
>>> d
{'b': 'hello', 'name': 'winner', 'price': 3.14, 'color': 'white', 'city': 'hangzhou'}
>>> d.popitem() //删除最后一对,并返回其值
('city', 'hangzhou')
5.7比较字典和列表
- 字典不是序列
- 两者都是容器类对象
- 两者都是可变对象
- python3.6开始,字典也有顺序
6、集合{}
(在数学中具有无序性、互异性、确定性三个特点)
- 可变集合
- 不可变集合
- 集合的特点
集合中的元素必须是不可变对象
>>> s = set([1,2,3,3,2,1,4])
>>> s
{1, 2, 3, 4}
>>> type(s)
<class 'set'>
>>> s2 = {'python',2,3}
>>> type(s2)
<class 'set'>
>>> s3 = {'python',[1,2,3]}
Traceback (most recent call last):
File "<pyshell#233>", line 1, in <module>
s3 = {'python',[1,2,3]}
TypeError: unhashable type: 'list'
因为集合中的元素是无序的,所以它没有索引
6.1集合中元素的增加和删除
>>> s
{1, 2, 3, 4}
>>> s.add('python')
>>> s
{1, 2, 3, 4, 'python'}
>>> s.pop()
1
>>> s.pop()
2
>>> s
{3, 4, 'python'}
>>> s.remove(4)
>>> s
{3, 'python'}
>>> s.discard(3)
>>> s
{'python'}
>>> s.discard(3) //使用discard删除不存在的元素不会报错
>>> s.remove(3) //使用remove删除不存在的元素会报错
Traceback (most recent call last):
File "<pyshell#247>", line 1, in <module>
s.remove(3)
KeyError: 3
6.2不可变集合
>>> f_set = frozenset('hrdhrh')
>>> f_set
frozenset({'h', 'd', 'r'})
6.3浅拷贝(三种容器类对象都具有的方法)
>>> b1 = ['name',123,['python','php']]
>>> b2 = b1.copy()
>>> b2
['name', 123, ['python', 'php']]
>>> b1 is b2
False
>>> b1[0]
'name'
>>> b1[0] is b2[0]
True
>>> b1[2] is b2[2]
True
>>>
>>> b1[0] = 100
>>> b1
[100, 123, ['python', 'php']]
>>> b2
['name', 123, ['python', 'php']]
//拷贝的是容器的第一层,里面的没有拷贝,如果容器里面还有容器,里面容器中的对象和原来的是同一个对象
>>> b1[2][0]
'python'
>>> b1[2][0] = 999
>>> b1
[100, 123, [999, 'php']]
>>> b2
['name', 123, [999, 'php']]
6.4深拷贝
>>> import copy
>>> b1
[100, 123, [999, 'php']]
>>> b3 = copy.deepcopy(b1)
>>> b3
[100, 123, [999, 'php']]
>>> b1[2][0] = 'java'
>>> b1
[100, 123, ['java', 'php']]
>>> b3
[100, 123, [999, 'php']]
6.5元素与集合的关系
>>> s = set('python')
>>> s
{'y', 'n', 'p', 'h', 't', 'o'}
>>> 'a' in s
False
>>> 'y' in s
True
>>> len(s)
6
6.6集合与集合的关系
>>> a = set([1,2,3,4,5])
>>> b = set([1,2,3])
>>> a.issuperset(a)
True
>>> a.issuperset(b)
True
>>> b.issubset(a)
True
6.7集合之间的运算
并集
>>> a
{1, 2, 3, 4, 5}
>>> b
{1, 2, 3}
>>> a|b
{1, 2, 3, 4, 5}
>>> a.union(b)
{1, 2, 3, 4, 5}
交集
>>> a & b
{1, 2, 3}
>>> a.intersection(b)
{1, 2, 3}
差集
>>> a - b
{4, 5}
>>> a.difference(b)
{4, 5}
7、python常见内置对象类型的案例
'''
例1:编写程序,根据输入的半径,计算圆的面积。
'''
import math
r = float(input("Enter the radius of circle:"))
area = math.pi * r * r
print("The area is :", round(area, 2))
'''
编写程序,利用“凯撒密码”方案,实现对用户输入文字的加密操作。
凯撒密码(英語:Caesar cipher),是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移後被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。
'''
letter = input("Please input an English letter: ")
n = 3
'''将letter转换为ASCII编码,然后加3'''
pwd = ord(letter) + n
'''将ASCII编码再转为字母'''
pwd_letter = chr(pwd)
print(letter, "==>", pwd_letter)
'''
编写程序,实现对输入字符串的大小写字母翻转
(即大写变小写、小写变大写)操作。
'''
word = input('please input an English word:')
new_lst = []
for i in word:
if i.islower():
new_lst.append(i.upper())
else:
new_lst.append(i.lower())
new_word = "".join(new_lst)
print(word, "==>", new_word)