来自一个 numpy 数组
a=np.arange(100).reshape(10,10)
我想获取一个数组
[[99, 90, 91],
[9, 0, 1],
[19, 10, 11]]
我试过了
a[[-1,0,1],[-1,0,1]]
但这反而给出了array([99, 0, 11])
。我该如何解决这个问题?
答案 0 :(得分:1)
a[[-1,0,1],[-1,0,1]]
这是错误的,这意味着您想要来自 row -1
, column -1
ie (99)
和 row 0
, column 0
ie { 的元素{1}} 和 (0)
, row 1
即 column 1
这就是你得到 array([99, 0, 11]) 的原因
您的答案:
(11)
:这意味着,我们希望第 a[ [[-1],[0],[1]], [-1,0,1] ]
列中的每个元素来自第 -1, 0, 1
行。
答案 1 :(得分:1)
在两个轴上滚动您的数组并切片 3x3:
Tile::Tile(sf::Sprite tile, sf::Sprite tile_hl, sf::Vector2f pos)
{
this->tile = tile;
this->tile_hl = tile_hl;
isHighlighted = (int)(pos.x /32) % 2 == 0;
//set position of a sprite
tile.setPosition(pos);
//reference points to address, tile I'm gonna to render
activeTile = isHighlighted ? &this->tile_hl : &this->tile;
}
Tile::Tile(const Tile& other)
{
tile = other.tile;
tile_hl = other.tile_hl;
isHighlighted = other.isHighlighted;
activeTile = isHighlighted ? &tile_hl : &tile;
}
void Tile::Draw(sf::RenderWindow& window)
{
if (isHighlighted)
{
activeTile = &this->tile_hl;
}
window.draw(*activeTile);
activeTile = &this->tile;
}
//whether we check highlights it will be set here
void Tile::SetHighlighted(bool flag)
{
// isHighlighted = flag;
}
答案 2 :(得分:1)
将切片分成两个单独的操作
arr[ [ -1,0,1] ][ :, [ -1,0,1]]
# array([[99., 90., 91.],
# [ 9., 0., 1.],
# [19., 10., 11.]])
相当于:
temp = arr[ [ -1,0,1] ] # Extract the rows
temp[ :, [ -1,0,1]] # Extract the columns from those rows
# array([[99., 90., 91.],
# [ 9., 0., 1.],
# [19., 10., 11.]])