Python 3 中,列表推导、生成器表达式以及集合推导、字典推导中,有自己的局部作用域,表达式内部的变量和赋值只在局部起作用,表达式的上下文里的同名变量还可以正常引用,局部变量并不影响它们。

  1. x = 'ABC'
  2. dummy = [ord(x) for x in x]
  3. print(x)
  4. # 'ABC'
  5. print(dummy)
  6. # [65, 66, 67]

但是在python2.x中,同名变量会相互影响。

Python 切片

基本语法

  1. slice(stop)
  2. slice(start, stop[, step])

例子:

  1. >>> a = list(range(10))
  2. >>> a
  3. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  4. >>> s = slice(3)
  5. >>> s
  6. slice(None, 3, None)
  7. >>> a[s] # a[:3]
  8. [0, 1, 2]
  9. >>> s = slice(2, 8)
  10. slice(2, 8, None)
  11. >>> a[s] # a[2:8]
  12. [2, 3, 4, 5, 6, 7]
  13. >>> s = slice(2,8,2)
  14. slice(2, 8, 2)
  15. >>> a[s] # a[2:8:2]
  16. [2, 4, 6]

特殊用法:

  • a的拷贝
  1. >>> slice(None)
  2. slice(None, None, None)
  3. >>> a[:]
  4. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  5. # a[None:None]
  6. # a[slice(None)]
  • 反向
  1. >>> a = list(range(10))
  2. >>> a[::-1]
  3. [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  4. >>> a[::-2]
  5. [9, 7, 5, 3, 1]
  6. >>> a[3::-1]
  7. [3, 2, 1, 0]

小计:

  • step为正数的时候,start < end,否则结果为 []
  • step为负数的时候,start > end,否则结果为 []
  1. -6 -5 -4 -3 -2 -1
  2. 0 1 2 3 4 5
  3. +---+---+---+---+---+---+
  4. | P | y | t | h | o | n |
  5. +---+---+---+---+---+---+
  6. 0 1 2 3 4 5 6
  7. -6 -5 -4 -3 -2 -1

切片赋值

  1. >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  2. >>> letters
  3. ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  4. >>> # replace some values
  5. >>> letters[2:5] = ['C', 'D', 'E']
  6. >>> letters
  7. ['a', 'b', 'C', 'D', 'E', 'f', 'g']
  8. >>> # now remove them
  9. >>> letters[2:5] = []
  10. >>> letters
  11. ['a', 'b', 'f', 'g']
  12. >>> # clear the list by replacing all the elements with an empty list
  13. >>> letters[:] = []
  14. >>> letters
  15. []

参考:stackoverflow: Understanding Python’s slice notation