[英]Python: how to use append random numbers of parameter in a list
My dataset has random dimensions, so that I want to use exec()
or eval()
to read in my data. 我的数据集具有随机维度,因此我想使用exec()
或eval()
读取数据。 Here is my code: 这是我的代码:
tim = []
var = []
for line in open(fid).readlines():
str = line.split()
if line.find('/') >= 0:
tim.append( datetime.strptime(str[0]+str[1],'%Y/%m/%d%H:%M:%S'))
depth = int(str[2])
num = 0
else:
if num == 0:
for i in range(len(str)): exec('var_%02d = []' %(i))
for i in range(len(str)): exec('var_%02d.append( str[%d] ) ' % (i,i))
num += 1
if num == depth-1:
var.append([eval('var_%02d' % i) for i in range(len(str))])
The format of data looks like: 数据格式如下:
2010/01/01 00:00:00 6 2
10 20
15 22
20 30
25 28
35 17
40 35
Sometimes the data may add another column and looks like: 有时数据可能会添加另一列,如下所示:
2010/01/01 00:00:00 6 2
10 20 18
15 22 21
20 30 30
25 28 28
35 17 17
40 35 32
Generally, my code works fine. 通常,我的代码可以正常工作。 But if I want to make if like a function, it is not working. 但是,如果我想使它像一个函数,那是行不通的。 Does anybody know how to append random numbers of parameters together in a list? 有人知道如何将随机数的参数一起添加到列表中吗?
You don't need to use exec
, actually you should never use exec
. 您不需要使用exec
,实际上您绝对不应该使用exec
。 Use a multidimensional array (an array of arrays) to collect your numbers: 使用多维数组(数组的数组)来收集数字:
tmp = []
tim = []
var = []
for line in open(fid).readlines():
str = line.split()
if line.find('/') >= 0:
tim.append( datetime.strptime(str[0]+str[1],'%Y/%m/%d%H:%M:%S'))
depth = int(str[2])
num = 0
else:
if num == 0:
for i in range(len(str)):
if len(tmp) <= i:
tmp.append([])
for i in range(len(str)):
tmp[i].append(str[i])
num += 1
if num == depth-1:
var.append([tmp[i] for i in range(len(str))])
print(var)
For the first set of data it will print: 对于第一组数据,它将打印:
[[['10', '15', '20', '25', '35', '40'], ['20', '22', '30', '28', '17', '35']]]
And for the second: 第二:
[[['10', '15', '20', '25', '35', '40'], ['20', '22', '30', '28', '17', '35'], ['18', '21', '30', '28', '17', '32']]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.