LoginSignup
2
3

More than 5 years have passed since last update.

Pythonのリスト/タプルからNumPy風に(indexのリストを使って)要素を抽出する

Posted at

こんな感じで出来る。

itemgetter_iterable_example.py
import numpy as np
from operator import itemgetter

np_list = np.linspace(0, 1, num=11)
# -> array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])
py_list = list(np_list)
indexes = [1, 3, 5]  # 適当なインデックス

# NumPyだとこんな感じ
np_list[indexes]
# -> array([ 0.1,  0.3,  0.5])

# Pythonのリストだとこんな感じ
itemgetter(*indexes)(py_list)
# -> (0.1, 0.3, 0.5)

NumPyに一回変換すればいいじゃん、っていう話もある。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3