公共方法
运算符
运算符 | Python | 表达式 | 结果 | 描述 | 支持的数据类型 |
---|
- | [1, 2] + [3, 4] | [1, 2, 3, 4] | 合并 | 字符串、列表、元组
- | ‘Hi!’ * 4 | [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] | 复制 | 字符串、列表、元组
in | 3 in (1, 2, 3) | True | 元素是否存在 字符串、| 列表、元组、字典
not in | 4 not in (1, 2, 3) | True | 元素是否不存在 | 字符串、列表、元组、字典 - *+**
>>> "hello " + "itcast" 'hello itcast' >>> [1, 2] + [3, 4] [1, 2, 3, 4] >>> ('a', 'b') + ('c', 'd') ('a', 'b', 'c', 'd')
>>> 'ab'*4
'ababab'
>>> [1, 2]*4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b')*4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')
in
>>> 'itc' in 'hello itcast'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"Delron", "age":24}
True
注意,in在对字典操作时,判断的是字典的键
python内置函数
Python包含了以下内置函数
序号 | 方法 | 描述
—— | —– |——-
1 | cmp(item1, item2) | 比较两个值
2 | len(item) | 计算容器中元素个数
3 | max(item) | 返回容器中元素最大值
4 | min(item) | 返回容器中元素最小值
5 | del(item) | 删除变量
引用
在python中,值是靠引用来传递来的。
我们可以用id()来判断两个变量是否为同一个值的引用。 我们可以将id值理解为那块内存的地址标示。
>>> a = 1
>>> b = a
>>> id(a)
13033816
>>> id(b) # 注意两个变量的id值相同
13033816
>>> a = 2
>>> id(a) # 注意a的id值已经变了
13033792
>>> id(b) # b的id值依旧
13033816
>>> a = [1, 2]
>>> b = a
>>> id(a)
139935018544808
>>> id(b)
139935018544808
>>> a.append(3)
>>> a
[1, 2, 3]
>>> id(a)
139935018544808
>>> id(b) # 注意a与b始终指向同一个地址
139935018544808
可变类型与不可变类型
可变类型,值可以改变:
- 列表 list
- 字典 dict
不可变类型,值不可以改变: - 数值类型 int, long, bool, float
- 字符串 str
- 元组 tuple