Python:根据列位置将嵌套数组转换为新格式化的嵌套数组

发布于 2025-01-19 10:24:19 字数 457 浏览 3 评论 0原文

假设我有一个像这样的嵌套数组:

array = [[1,7], [49, 9], [3, 80], [13, 15]]

从上面的数组中,我想根据垂直“列”创建两个新数组(在嵌套数组中)。这是我所需的输出:

new_array = [[1, 49, 3, 13], [7, 9, 80, 15]]

我希望逻辑能够工作天气,我的长度为2(如我的示例)或30(或更多)(或更多)。

我尝试使用词典来做到这一点。代码的逻辑看起来像这样,但字典并未产生我要寻找的内容:

featureCol["valuesList{}".format(i)].append(nestedArray[i])   

另外,我唯一可以使用的库是numpy。我在Python中没有其他可用的图书馆。

Let's say I have a nested array like so:

array = [[1,7], [49, 9], [3, 80], [13, 15]]

From the above array, I want to create two new arrays (within a nested array) based on vertical "columns". This is my desired output:

new_array = [[1, 49, 3, 13], [7, 9, 80, 15]]

I want the logic to work weather I have individually nested arrays of length 2 (as in my example) or 30 (or more).

I tried using a dictionary to do this. The logic of the code looked something like this but the dictionary is not producing what I'm looking for:

featureCol["valuesList{}".format(i)].append(nestedArray[i])   

Also, the only library I can use is numpy. I don't have any additional libraries available to me in Python.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没︽人懂的悲伤 2025-01-26 10:24:19

您可以使用 zip() 进行列表解包。此操作假设所有输入列表的长度相同,但不会对输入列表的大小做出任何假设,否则:

result = list(list(item) for item in zip(*array))
print(result)

此输出:

[[1, 49, 3, 13], [7, 9, 80, 15]]

You can use zip() with list unpacking. This operation assumes that all of the input lists are of the same length, but it does not make any assumptions on the sizes of the input lists otherwise:

result = list(list(item) for item in zip(*array))
print(result)

This outputs:

[[1, 49, 3, 13], [7, 9, 80, 15]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文