python中area是什么意思_从python中的2D数组中选择'area'

Is there a way to select a particular 'area' of a 2d array in python?

I can use array slicing to project out only one row or column but I am unsure about how to pick a 'subarray' from the large 2d array.

Thanks in advance

Jack

解决方案

If you are using the numpy library, you can use numpy's more advanced slicing to accomplish this like so:

import numpy as np

x = np.array([[1, 2, 3, 4],

[5, 6, 7, 8],

[9, 10, 11, 12]])

print x[0:2, 2:4]

# ^^^ ^^^

# rows cols

# Result:

[[3 4]

[7 8]]

(more info in the numpy docs)

If you don't want to use numpy, you can use a list comprehension like this:

x = [[1, 2, 3, 4],

[5, 6, 7, 8],

[9, 10, 11, 12]]

print [row[2:4] for row in x[0:2]]

# ^^^ ^^^ select only rows of index 0 or 1

# ^^^ and only columns of index 2 or 3

# Result:

[[3, 4],

[7, 8]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值