将数组列表合并到一个数组列表中 [英] Merge array lists into one array list

查看:459
本文介绍了将数组列表合并到一个数组列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题上,我花了比我愿意接受的更多的时间. 我有一个函数:

I spent more time on this issue than I am willing to admit. I have a function called:

def array_funct(filename):
...
 data = np.array((array))
 return data

从文件夹中读取.txt文件,并返回一个numpy数组.

which reads in .txt files from a folder and returns a numpy array.

第一个是x坐标的列表,第二行是对应的y坐标.因此,我使用:

The first row is a list of x coordinates and second row are the cooresponding y coordinates. Hence I use:

array_funct(filename)[:,0]
array_funct(filename)[:,1]

访问x和y坐标.

现在我要做的就是创建一个for循环,该循环将读取多个文件并按照以下方式存储它们

Now all I want to do is to create a for loop which would read in more than 1 file and store them in following way

for i in range(0,number_of_files):

    array_funct(file[i])[:,0]
    array_funct(file[i])[:,1]

让我们看看我得到的x列表:

Let's look at the x-lists which I get:

print(array_funct(file[0])[:,0])  
[1,2,3,4]
print(array_funct(file[1])[:,0]) 
[2,4,6,8]

我想要做的就是获取这两个类似numpy的列表并创建:

All I want is to take these two numpy like lists and create:

x_tot = [[1,2,3,4], [2,4,6,8]]

这样我就可以像这样明智地访问单个列表元素:

such that I can access the single lists element wise like:

x_tot[0] = [1,2,3,4]

好难吗?我应该停止使用numpy array吗?如果可能的话,我想呆在numpy中.

Is that so hard? Should I stop using numpy array ? I would like to stay in numpy if possbile.

还请记住,我仅针对2个文件制作了此示例,但可能还会更多.我只想为要读取的可变数量的文件创建一个x_tot和y_tot.这样:

Also keep in mind that I made this example for just 2 files but it could be more. I just want to create a x_tot and y_tot for a variable amount of files I would read in. Such that:

x_tot = [[1,2,3],[2,3,4],[..],..]
x_tot = [[2,4,6],[4,6,8],[..],..]

推荐答案

给出以下array_funct函数和filenames列表:

def array_funct(filename):
    # Fake random data, replace with data read from file
    data_read = [[1,2,3,4], [5,6,7,8]] # [random.sample(range(1, 10), 7), random.sample(range(1, 10), 7)]  
    data = np.array(data_read) 
    return data

filenames = ['file1.txt', 'file2.txt']

尝试以下代码:

lx = [list(array_funct(file)[0]) for file in filenames]
ly = [list(array_funct(file)[1]) for file in filenames]

或者通过一次阅读和滚动文件来提高效率:

Or more efficiently by reading and scrolling the file once:

all_data = [(list(arr[0]),list(arr[1])) for arr in [array_funct(f) for f in filenames]]
lx, ly = list(map(list, zip(*all_data)))

在两种情况下,输出如下:

In both cases, the output is as follows:

# lx = [[1, 2, 3, 4], [1, 2, 3, 4]]
# ly = [[5, 6, 7, 8], [5, 6, 7, 8]]

这篇关于将数组列表合并到一个数组列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆