1. 程式人生 > >Python入門:零碎知識點

Python入門:零碎知識點

矩陣 ber pos 二維 () ans transpose arr code

  • zip()

用於將可叠代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。

如果各個叠代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。

  1. a = [1,2,3]
  2. b = [4,5,6]
  3. c = [4,5,6,7,8]
  4. zipped = zip(a,b) # 打包為元組的列表
  5. print(zipped)
  6. # [(1, 4), (2, 5), (3, 6)]
  7. print(zip(a,c)) # 元素個數與最短的列表一致
  8. # [(1, 4), (2, 5), (3, 6)]
  9. print(zip(*zipped)) # 與 zip 相反,*zipped 可理解為解壓,返回二維矩陣式
  10. # [(1, 2, 3), (4, 5, 6)]
  • np.squeeze()

從數組的形狀中刪除單維條目,即把shape中為1的維度去掉

np.squeeze(images)
  • np.transpose()

矩陣轉置

  1. arr = np.arange(16).reshape((2, 2, 4))
  2. ‘‘‘
  3. [[[ 0, 1, 2, 3],
  4. [ 4, 5, 6, 7]],
  5. [[ 8, 9, 10, 11],
  6. [12, 13, 14, 15]]]
  7. ‘‘‘
  8. arr.transpose((1,0,2))
  9. ‘‘‘
  10. [[[ 0, 1, 2, 3],
  11. [ 8, 9, 10, 11]],
  12. [[ 4, 5, 6, 7],
  13. [12, 13, 14, 15]]]
  14. ‘‘‘
  15. arr.transpose((0,2,1))
  16. ‘‘‘
  17. [[[ 0, 4],
  18. [ 1, 5],
  19. [ 2, 6],
  20. [ 3, 7]],
  21. [[ 8, 12],
  22. [ 9, 13],
  23. [10, 14],
  24. [11, 15]]]
  25. ‘‘‘
  26. arr.transpose((1,2,0))
  27. ‘‘‘
  28. [[[ 0, 8],
  29. [ 1, 9],
  30. [ 2, 10],
  31. [ 3, 11]],
  32. [[ 4, 12],
  33. [ 5, 13],
  34. [ 6, 14],
  35. [ 7, 15]]]
  36. ‘‘‘

www.hanbotec.com
來源瀚博圖像轉載請註明

Python入門:零碎知識點