首页 > 解决方案 > 使用列表作为函数输入时的输出列表理解

问题描述

我有一个函数func,它有一个nxn数组和一个线性空间np.arange(0,10,1)作为输入。

如何同时遍历这个数组和线性空间,以创建一个数组,其中行是func线性空间中的返回值?

作为 MWE:

import numpy as np

def func(x,t):
      return t+x

ts = [[1,2],
      [5,6],
      [9,10]]

x_axis = np.arange(0,5,~1)

empty = [[] for i in range(3)]

for t, j in enumerate(ts):
      for th in j:
            empty[t] = []
            for x in x_axis:
                  empty[t].append(func(x,t))
print(empty)

输出:

[[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]

期望输出:

[[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[5, 6, 7, 8, 9],
[6, 7, 8, 9, 10],
[9, 10, 11, 12, 13],
[10, 11, 12, 13, 14]]

我可能将数组与列表混合在一起,并且可能 append() 不是这项工作的方法。谢谢!

标签: pythonarrayslistfunctionloops

解决方案


推荐阅读