1. 运算符

运算符 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 元素是否不存在 字符串、列表、元组、字典

+

  1. >>> "hello " + "itcast"
  2. 'hello itcast'
  3. >>> [1, 2] + [3, 4]
  4. [1, 2, 3, 4]
  5. >>> ('a', 'b') + ('c', 'd')
  6. ('a', 'b', 'c', 'd')

*

  1. >>> 'ab' * 4
  2. 'ababab'
  3. >>> [1, 2] * 4
  4. [1, 2, 1, 2, 1, 2, 1, 2]
  5. >>> ('a', 'b') * 4
  6. ('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

in

  1. >>> 'itc' in 'hello itcast'
  2. True
  3. >>> 3 in [1, 2]
  4. False
  5. >>> 4 in (1, 2, 3, 4)
  6. True
  7. >>> "name" in {"name":"Delron", "age":24}
  8. True

注意,in在对字典操作时,判断的是字典的键

2. python内置函数

Python包含了以下内置函数

序号 函数 描述
1 len(item) 计算容器中元素个数
2 max(item) 返回容器中元素最大值
3 min(item) 返回容器中元素最小值
4 del(item) 删除变量

len

  1. >>> len("hello itcast")
  2. 12
  3. >>> len([1, 2, 3, 4])
  4. 4
  5. >>> len((3,4))
  6. 2
  7. >>> len({"a":1, "b":2})
  8. 2

注意:len在操作字典数据时,返回的是键值对个数。

max

  1. >>> max("hello itcast")
  2. 't'
  3. >>> max([1,4,522,3,4])
  4. 522
  5. >>> max({"a":1, "b":2})
  6. 'b'
  7. >>> max({"a":10, "b":2})
  8. 'b'
  9. >>> max({"c":10, "b":2})
  10. 'c'

del

del有两种用法,一种是del加空格,另一种是del()

  1. >>> a = 1
  2. >>> a
  3. 1
  4. >>> del a
  5. >>> a
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. NameError: name 'a' is not defined
  9. >>> a = ['a', 'b']
  10. >>> del a[0]
  11. >>> a
  12. ['b']
  13. >>> del(a)
  14. >>> a
  15. Traceback (most recent call last):
  16. File "<stdin>", line 1, in <module>
  17. NameError: name 'a' is not defined

3. 多维列表/元祖访问的示例

  1. >>> tuple1 = [(2,3),(4,5)]
  2. >>> tuple1[0]
  3. (2, 3)
  4. >>> tuple1[0][0]
  5. 2
  6. >>> tuple1[0][2]
  7. Traceback (most recent call last):
  8. File "<stdin>", line 1, in <module>
  9. IndexError: tuple index out of range
  10. >>> tuple1[0][1]
  11. 3
  12. >>> tuple1[2][2]
  13. Traceback (most recent call last):
  14. File "<stdin>", line 1, in <module>
  15. IndexError: list index out of range
  16. >>> tuple2 = tuple1+[(3)]
  17. >>> tuple2
  18. [(2, 3), (4, 5), 3]
  19. >>> tuple2[2]
  20. 3
  21. >>> tuple2[2][0]
  22. Traceback (most recent call last):
  23. File "<stdin>", line 1, in <module>
  24. TypeError: 'int' object is not subscriptable