是否可以在python中保存和访问并搜索包含不同长度元素的数组或列表?

时间:2018-04-20 06:19:22

标签: arrays python-3.x list array-difference variable-length

是否可以保存和访问包含不同长度元素的数组或列表?例如,我想保存data=[s,r,a,se] r,a是标量但是sse是一个包含4个元素的数组。(用python语言)

例如,在一次中:(s,r,a,se)在不同时间有所不同

 s=[1,3,4,6] r=5 a=7 se=[11,12,13,14] 
 data=[s,r,a,se]=[[1,3,4,6],5,7,[11,12,13,14]]

如何定义包含它们的数组,以便能够调用它们,类似于以下代码:

s=[data[0] for data in minibatch]
r=[data[1] for data in minibatch]
a=[data[2] for data in minibatch]
se=[data[3] for data in minibatch]

此外,我如何提取(查找[stest,rtest,atest,setest]中的特殊datastest,setest有4个元素)

例如:我希望看到我能在数据中找到[[1,2,3,4],5,6,[7,8,9,10]],类似于:[ [[1,2,3,4],5,6,[7,8,9,10]] ,[[...,...,...,...],...,..., [...,...,...,...]], [[18,20,31,42],53,666,[27,48,91,120]]]

如果我没有找到,我会附加它,否则什么也没发生!

2 个答案:

答案 0 :(得分:1)

您可以将它们添加到新列表中:

 new_list = [s, r, a, se]

但是你必须小心管理这个清单

答案 1 :(得分:0)

# This is a great opportunity to explore dictionaries

# lets take the examples you have given in variales
s=[1,3,4,6] 
r=5 
a=7 
se=[11,12,13,14]

# make a dictionary out of them, with keys which are 
# the same as the variable name
my_dict = {'s':s,
           'r':r,
           'a':a,
           'se':se}

# lets see what that looks like
print(my_dict)
print()

# to retrieve 2nd (=ix=1) element of s
# the format to do this is simple
# ditionary_variable_name['the string which is the key'][index_of_the_list]
s2 = my_dict['s'][1]
print(s2)
print()

# to retrieve all of se
se_retrieved = my_dict['se']
print(se_retrieved)

# you can further experiment with this

样本输出:

{'s': [1, 3, 4, 6], 'r': 5, 'a': 7, 'se': [11, 12, 13, 14]}

3

[11, 12, 13, 14]

为了写这篇文章,你需要做这样的事情:

my_dict['se'] = [15, 16, 17, 18]

my_dict['se'][2] = 19