VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • Python之List列表如何处理最好?正确案例详解(2)

, 2))) [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] >>> list(map(list, combinations(a, 2))) [[1, 2], [1, 3], [2, 3]] >>> b = [4, 5, 6] >>> list(map(list, product(a, b))) [[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]] >>> list(map(list, product(a, repeat=2))) [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
  1. 列表转置
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> list(map(list, zip(*a)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

 

 

Python 列表常用方法

  1. 建立列表
  • 直接建立
>>> [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
  • 函数 / 方法 / 产生器建立
>>> [i for i in range(5)]
[0, 1, 2, 3, 4]
  • 一维双变量交互建立
>>> [(i, j*10) for i in range(5) for j in range(5)]
[(0, 0), (0, 10), (0, 20), (0, 30), (0, 40), (1, 0), (1, 10), (1, 20), ( 1, 30), (1, 40), (2, 0), (2, 10), (2, 20), (2, 30), (2, 40), (3, 0), (3, 10), (3, 20), (3, 30), (3, 40), (4, 0), (4, 10), (4, 20), (4, 30), (4, 40) ]
  • 一维双变量对应建立
>>> [(i, j*10) for i, j in zip(range(5), range(5))]
[(0, 0), (1, 10), (2, 20), (3, 30), (4, 40)]
  • 多维列表建立
>>> [[[i, j] for i in range(5)] for j in range(5)]
[[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]],
 [[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]],
 [[0, 2], [1, 2], [2, 2], [3, 2], [4, 2]],
 [[0, 3], [1, 3], [2, 3], [3, 3], [4, 3]],
 [[0, 4], [1, 4], [2, 4], [3, 4], [4, 4]]]
  • 从其他变量建立
>>> list('We are the world')
['W', 'e', ' ', 'a', 'r', 'e', ' ', 't', 'h', 'e', ' ', 'w', 'o', 'r', 'l', 'd']
>>> list(range(5))
[0, 1, 2, 3, 4]
  1. 修改列表
  • 单一元素修改
>>> a = [1, 2, 3, 5]
>>> a[3] = 4
>>> a
[1, 2, 3, 4]
  • 部份修改
>>> a[1:3] = [5, 6]
[1, 5, 6, 4]
>>> a[1:3] = [8]
[1, 8, 4]
  1. 复制列表
  • 记忆体参考位置复制
>>> a = [1, 2, 3, 4]
>>> b = a
>>> b[1] = 10
>>> a, b
([1, 10, 3, 4], [1, 10, 3, 4])
  • 一维浅层复制
>>> from copy import copy, deepcopy
>>> a = [[1,2,3], [4, 5,6]]
>>> b = copy(a) # 同 b = a[:]
>>> b[
      



  

相关教程