繁体   English   中英

如何分配与输入参数相对应的未知数量的变量

[英]How to allocate an unknown number of variables corresponding to input arguments

我有n个文件.txt,其中每个文件都包含一个矩阵。 我想为每个矩阵分配一个变量,读取相应的文件。

我不知道先验命令行参数指定的文件数量。

因此,我需要一种“ for循环”,它一次读取一个文件,并将相应的矩阵分配给变量。

例如:

python allocate_matrices.py file1 file2 file3

其中:file1是:

0 1 2
3 4 5
6 7 8

file2是:

0 1
3 4
6 7

和file3是:

0 1 2 5
3 4 5 6
6 7 8 7

我的想法是使用一种循环:

import numpy as np

for i in range(len(sys.argv)-1):
    file[i] = np.loadtxt(sys.argv[i+1])

但我不知道我应该使用哪种结构...

我不知道先验命令行参数指定的文件数量。

确保您这样做: len(sys.argv) - 1

即使您没有这样做,Python中的列表也不是固定大小的。 那么为什么不这样做:

matrices = []                       # Allocate an empty list
for filename in sys.argv[1:]:       # Skip argv[0], name of script
    mat = np.loadtxt(filename)      # Read a matrix
    matrices.append(mat)            # Append it to the list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM