LoginSignup
1
0

More than 5 years have passed since last update.

Python3 + Numpy > 5列の要素を持つ二次元リストから1列だけ取出す > PyMieScatt実装(内包表記) | np.array(lists)[:, 2:2+1].flatten() > よりシンプルな書き方

Last updated at Posted at 2018-04-01
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04.4 LTS desktop amd64
TensorFlow v1.7.0
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
scipy v0.19.1
geopandas v0.3.0
MATLAB R2017b (Home Edition)
ADDA v.1.3b6
gnustep-gui-runtime v0.24.0-3.1

_qDにはリスト形式でMie散乱の計算結果(qext, qsca, qabs...)が二次元データとして格納されている。
その取り出しは以下の内包表記で実施している。

qext = np.array([q[0] for q in _qD])

他の方法も考えてみた。

extractArray_180401.py
import numpy as np

# on Python 3.5.2

# 1. preparation
template = [3, 1, 4, 1, 5]
print(template)
lists = [template for loop in range(5)]
print(lists)
print('---')

# 2. Extract
PICKUP_INDEX = 2

# 2a. based on the PyMieScatt > MieQ_withDiameterRange()
item1a = np.array([q[PICKUP_INDEX] for q in lists])
print(item1a)

# 2b. this time
item1b = np.array(lists)[:, PICKUP_INDEX:PICKUP_INDEX+1].flatten()
print(item1b)
$ python3 extractArray_180401.py 
[3, 1, 4, 1, 5]
[[3, 1, 4, 1, 5], [3, 1, 4, 1, 5], [3, 1, 4, 1, 5], [3, 1, 4, 1, 5], [3, 1, 4, 1, 5]]
---
[4 4 4 4 4]
[4 4 4 4 4]

np.array(lists)[:, 2:2+1]のままでは[[4][4][4][4][4]]のようになる。[4 4 4 4 4]にするため、flatten()を加えている。
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

上記のような実装の場合、内包表記の方が可読性が良さそう。

関連

謝辞 > よりシンプルな書き方

@shiracamus さんのコメントにて、よりシンプルな書き方を教えていただきました。

情報感謝です。

1
0
3

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
1
0