【问题标题】:Are there ways to form a list from two arrays without using for loop?有没有办法在不使用 for 循环的情况下从两个数组形成一个列表?
【发布时间】:2021-06-16 14:44:15
【问题描述】:

我有两个数组,比如YX,它们都是三维数组,比如2X3X4。我想构建一个像[(X[0][0][0],Y[0][0][0]),(X[0][0][1],Y[0][0][1]),...,X[1][2][3],Y[1][2][3]] 这样的列表。在python中有没有不使用for循环的方法呢?

【问题讨论】:

  • x[0,0,0] 更容易阅读
  • 为什么要列表?

标签: python arrays python-3.x list numpy


【解决方案1】:

您可以先将数组展平为一维数组

import numpy as np
a = np.random.rand(2, 3, 4) # shape is (2, 3, 4)
a = a.reshape(24)      # shape is (24,) so flattened

b = np.random.rand(2, 3, 4)
b = b.reshape(24)

然后zip他们配对

r = list(zip(a, b))
print(r) # [(10, 1), (20, 2), (30, 3), (40, 4), (50, 5), (60, 6), (100, 10), (110, 11), (120, 12), (130, 13), (140, 14), (150, 15)]

【讨论】:

    猜你喜欢
    • 2019-06-17
    • 2020-12-20
    • 2023-03-07
    • 1970-01-01
    • 2019-01-18
    • 2016-05-12
    • 2021-10-09
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多