如何将numpy数组转换为元组 [英] how to convert numpy array into tuple
问题描述
我需要像这样转换数组:
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数组转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!