如何将numpy数组转换为元组

编程入门 行业动态 更新时间:2024-10-28 08:17:14
本文介绍了如何将numpy数组转换为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要像这样转换数组:

I need to convert array like this:

[[1527 1369 86 86] [ 573 590 709 709] [1417 1000 68 68] [1361 1194 86 86]]

要这样:

[(726, 1219, 1281, 664), (1208, 1440, 1283, 1365), (1006, 1483, 1069, 1421), (999, 1414, 1062, 1351),]

我尝试直接将convert转换为元组,但是得到了:

I tried using convert diretly to tuple but got this:

( array([1527, 1369, 86, 86], dtype=int32), array([573, 590, 709, 709], dtype=int32), array([1417, 1000, 68, 68], dtype=int32), array([1361, 1194, 86, 86], dtype=int32)) (array([701, 899, 671, 671], dtype=int32),)

推荐答案

数组方法tolist是将数组转换为列表的简便方法.它可以正确处理多个尺寸:

The array method tolist is a easy and fast way of converting an array to a list. It handles multiple dimensions correctly:

In [92]: arr = np.arange(12).reshape(3,4) In [93]: arr Out[93]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [94]: arr.tolist() Out[94]: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

在大多数情况下,例如列表列表与元组列表或元组列表一样好.它们仅在可变性方面有所不同.

For most purposes such as list of lists is just as good as a list of tuples, or tuple of tuples. They differ only in mutability.

但是如果您必须有一个元组,则列表理解可以很好地进行转换.

But if you must have a tuples, a list comprehension does the conversion nicely.

In [95]: [tuple(x) for x in arr.tolist()] Out[95]: [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]

替代的[tuple(x) for x in arr]有点慢,因为它在数组而不是列表上进行迭代.它也会产生不同的结果-尽管您必须检查元组元素的type才能看到结果.

An alternative [tuple(x) for x in arr] is a bit slower, because it is iterating on the array rather than on a list. It also produces a different result - though you have to examine the type of the tuple elements to see that.

我强烈建议从tolist方法开始,然后再进行任何列表以进行元组转换.

I strongly recommend starting with the tolist method, and doing any list to tuple conversions after.

更多推荐

如何将numpy数组转换为元组

本文发布于:2023-07-13 03:25:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1099800.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   如何将   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!