将两个数组合并为一个数组列表
Merge two arrays into an list of arrays
您好,我正在尝试使用 for 循环编译我在字典中的一堆数组,但我似乎找不到合适的解决方案。
基本上我所拥有的简化形式:
dict['w1']=[1,2,3]
dict['w2']=[4,5,6]
dict['w3']=[7,8]
x = []
for i in range(3):
x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0)
它给出了什么:
x = [1,2,3,4,5,6,7,8]
我想要的:
x = [[1,2,3],[4,5,6],[6,7]]
我想使用 for 循环,因为我有太多数组 'compile' 并且不能一个一个地键入它们会非常低效。这样我就可以使用创建的数组直接绘制箱线图了。
存在一个没有循环要求的类似问题,但仍然没有正确的解决方案。 Link
只是 append
列表中的项目。请注意,顺便说一句,如果您未指定起始值并将结束值视为 独占 边界,则 range
以 0
开头:
x = []
for i in range(1, 4):
x.append(dict['w' + str(i)])
一种方法是根据键获取 argsort 索引,并使用这些索引将 elements/values 从字典中排序出来,就像这样 -
np.take(dict.values(),np.argsort(dict.keys()))
如果您需要列表作为输出,请添加 .tolist()
。
样本运行-
In [84]: dict
Out[84]: {'w1': [4, 8, 2, 1], 'w2': [1, 3, 8], 'w3': [3, 2]}
In [85]: np.take(dict.values(),np.argsort(dict.keys()))
Out[85]: array([[4, 8, 2, 1], [1, 3, 8], [3, 2]], dtype=object)
In [86]: np.take(dict.values(),np.argsort(dict.keys())).tolist()
Out[86]: [[4, 8, 2, 1], [1, 3, 8], [3, 2]]
理解:
# using name as "dict" is not proper use "_dict" otherwise.
dict['w1']=[1,2,3]
dict['w2']=[4,5,6]
dict['w3']=[7,8]
x = [dict["w"+str(i)] for i in range(1, 4)]
给出输出:
[[1, 2, 3], [4, 5, 6], [7, 8]]
如果您指的是列表而不是字典,那么您正在寻找 zip 命令。
邮编 (w1,w2,w3)
您好,我正在尝试使用 for 循环编译我在字典中的一堆数组,但我似乎找不到合适的解决方案。
基本上我所拥有的简化形式:
dict['w1']=[1,2,3]
dict['w2']=[4,5,6]
dict['w3']=[7,8]
x = []
for i in range(3):
x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0)
它给出了什么:
x = [1,2,3,4,5,6,7,8]
我想要的:
x = [[1,2,3],[4,5,6],[6,7]]
我想使用 for 循环,因为我有太多数组 'compile' 并且不能一个一个地键入它们会非常低效。这样我就可以使用创建的数组直接绘制箱线图了。
存在一个没有循环要求的类似问题,但仍然没有正确的解决方案。 Link
只是 append
列表中的项目。请注意,顺便说一句,如果您未指定起始值并将结束值视为 独占 边界,则 range
以 0
开头:
x = []
for i in range(1, 4):
x.append(dict['w' + str(i)])
一种方法是根据键获取 argsort 索引,并使用这些索引将 elements/values 从字典中排序出来,就像这样 -
np.take(dict.values(),np.argsort(dict.keys()))
如果您需要列表作为输出,请添加 .tolist()
。
样本运行-
In [84]: dict
Out[84]: {'w1': [4, 8, 2, 1], 'w2': [1, 3, 8], 'w3': [3, 2]}
In [85]: np.take(dict.values(),np.argsort(dict.keys()))
Out[85]: array([[4, 8, 2, 1], [1, 3, 8], [3, 2]], dtype=object)
In [86]: np.take(dict.values(),np.argsort(dict.keys())).tolist()
Out[86]: [[4, 8, 2, 1], [1, 3, 8], [3, 2]]
理解:
# using name as "dict" is not proper use "_dict" otherwise.
dict['w1']=[1,2,3]
dict['w2']=[4,5,6]
dict['w3']=[7,8]
x = [dict["w"+str(i)] for i in range(1, 4)]
给出输出:
[[1, 2, 3], [4, 5, 6], [7, 8]]
如果您指的是列表而不是字典,那么您正在寻找 zip 命令。
邮编 (w1,w2,w3)