python如何把数组变成元组,如何将numpy数组转换为元组

I need to convert array like this:

[[1527 1369 86 86]

[ 573 590 709 709]

[1417 1000 68 68]

[1361 1194 86 86]]

to like this:

[(726, 1219, 1281, 664),

(1208, 1440, 1283, 1365),

(1006, 1483, 1069, 1421),

(999, 1414, 1062, 1351),]

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),)

解决方案

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)]

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.

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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值