1.变量
>>> A = [1,2,3,4,5]
>>> print(A)
[1, 2, 3, 4, 5]
>>> B=[1,2,3]
>>> print(B)
[1, 2, 3]
>>> A*3+B+A
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 3, 4, 5]
变量名尽量要有意义
>>> skill = ['新月打击','苍白之瀑']
>>> print(skill)
['新月打击', '苍白之瀑']
2.变量的命名规则
(1)变量名尽量使用字母、数字、下划线进行命名,但首字母不可以是数字,符号不可用*,$等。。
(2)系统关键字、保留关键字不可用于命名变量,如and,if,import....
(3)变量名区分大小写
>>> A = [1,2,3,4,5]
>>> a = (1,2,3)
>>> print (a)
(1, 2, 3)
>>> print(A)
[1, 2, 3, 4, 5]
(4)变量没有类型区分
字符串、数字、列表、元组都可以赋值给某变量
3.值类型和引用类型
>>> a = 1
>>> b = a
>>> a = 3
>>> print(b)
1
>>> a = [1,2,3,4]
>>> b = a
>>> a[0] = 7
>>> print(b)
[7, 2, 3, 4]
int str tuple 值类型 不可变
list set dict 引用类型 可变
举例
>>> a = 'hello'
>>> id(a)
67807744 //在内存的地址,一般16进制
>>> hex(id(a))
'0x3bf2a70'
>>> a = a + ' python'
>>> id(a)
62859888
a = a + ' python'看似是str是可变的,其实不是的,因为a + ' python'生成了一个新的字符串,再赋值给a,str依然是不可变的
再通过另一个例子,证明str的不可变性
>>> 'python'[0]
'p'
>>> 'python'[0] = 'r'
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
'python'[0] = 'r'
TypeError: 'str' object does not support item assignment
4.列表的可变和元组的不可变
>>> a = [1,2,3]
>>> id(a)
14402824
>>> a[0] = '1'
>>> id(a)
14402824
列表中某一元素改变,内存地址不发生改变
>>> b = (1,2,3)
>>> id (b)
14364384
>>> b[0] = '1'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
b[0] = '1'
TypeError: 'tuple' object does not support item assignment
>>> b.append(4)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
b.append(4)
AttributeError: 'tuple' object has no attribute 'append'
列表支持append追加
>>> c = [1,2,3]
>>> c.append(4)
>>> print(c)
[1, 2, 3, 4]
5.多维列表和数组
>>> d = [1,2,3,[4,5,6]]
>>> d[2]
3
>>> d[3][1]
5
>>> d = [1,2,3,[4,5,['1','2']]]
>>> d[3][2][1]
'2'
>>> d = (1,2,3,(4,5,6))
>>> d[2]
3
>>> d[3][1]
5
>>> d = (1,2,3,(4,5,('1','2')))
>>> d[3][2][1]
'2'
元组里有列表时,列表里的元素是不是可变的呢?
>>> d = (1,2,3,(4,5,['1','2']))
>>> d[3][2][1] = '8'
>>> print(d)
(1, 2, 3, (4, 5, ['1', '8']))
网友评论