Top / Python / TIPS集

NumPy?でfor文

[print(y[i]) for i in range(y.shape[0])]

遅いからあんまりよろしくないみたいですね

配列データを追加する

>>> import numpy as np
>>> a = np.empty((0,10))
>>> a
array([], shape=(0, 10), dtype=float64)
>>> a = np.append(a,[ [0,  1,  2,  3,  4,  5,  6,  7,  8,  9]], axis=0)
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> a= np.append(a,[ [0,  1,  2,  3,  4,  5,  6,  7,  8,9]], axis=0)
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> a= np.append(a,[ [0,  1,  2,  3,  4,  5,  6,  7,  8,9]], axis=0)
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> 

データ列をくっつける、分割する。

https://note.nkmk.me/python-numpy-split/

>>> import numpy as np
>>> data_size = 10
>>> x = np.random.choice(data_size,10,replace = False)
>>> x
array([8, 6, 1, 5, 2, 7, 9, 4, 0, 3])
>>> f = lambda x: x**2.0
>>> y = f(x)
>>> y
array([64., 36.,  1., 25.,  4., 49., 81., 16.,  0.,  9.])
>>> np.stack([x,y],axis=1)
array([[ 8., 64.],
       [ 6., 36.],
       [ 1.,  1.],
       [ 5., 25.],
       [ 2.,  4.],
       [ 7., 49.],
       [ 9., 81.],
       [ 4., 16.],
       [ 0.,  0.],
       [ 3.,  9.]])
>>> np.stack([x,y])
array([[ 8.,  6.,  1.,  5.,  2.,  7.,  9.,  4.,  0.,  3.],
       [64., 36.,  1., 25.,  4., 49., 81., 16.,  0.,  9.]])
>>>

分割は、

>>> X,Y=np.split(z,2,axis=1)
>>> X
array([[8.],
       [6.],
       [1.],
       [5.],
       [2.],
       [7.],
       [9.],
       [4.],
       [0.],
       [3.]])
>>> Y
array([[64.],
       [36.],
       [ 1.],
       [25.],
       [ 4.],
       [49.],
       [81.],
       [16.],
       [ 0.],
       [ 9.]])
>>> 

切り捨て除算

>>> 20 / 3
6.666666666666667
>>> 20.0 / 3.0
6.666666666666667
>>> 20.0 // 3.0
6.0
>>> 20 // 3
6
>>> 

HTTP(s)リクエストで、プロキシを通す件

 proxies = {
     "http": "http://username:password@proxy:8888",
     "https": "http://username:password@proxy:8888"
 }

 r = requests.post(
     'https://labs.goo.ne.jp/api/morph',
     data=payload.encode('utf-8').decode('latin-1'),
     headers=headers,
     proxies=proxies,
     verify=False)

などでOK。SSLのチェックはverify=FalseでOFFにしている。また、プロキシサーバにしたPCのFW設定も要チェック*1

複数の戻り値を返す件。

Pythonの関数で複数の戻り値を返す方法 | note.nkmk.me

タプル型というので返すと、複数の戻り値を返せる。コレめっちゃ便利なのでは。。

クラスのメンバ変数にはアンスコを二つつける件

9. クラス ― Python 2.7.14 ドキュメント

printf の書式設定

printf("Switchの状態:{0}".format(isClick)) #formatの第一引き数を表示
printf("Counter: [{0:3.1f}]".format(counter/interval)) # 全体で3桁、小数点1桁

って感じに文字列のformat関数というのでフォーマット可能。

Python3におけるformat形式を自分のためにまとめてみた件 - どこかに向かうらしい話

Pythonでsubstring

key = 'temperature_130010.json'
city_code = key[len('temperature_'):-5]
-> 130010

設定ファイルをあつかう

設定ファイル (ConfigParser) - Python入門から応用までの学習サイト

詳しく書いてあります。。

Javaのlongの日付をあつかう

long dateLong = 1480232552192L;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date(dateLong);
System.out.println(df.format(date));
System.out.println(date.getTime());

実行結果

2016/11/27 16:42:32.192
1480232552192
from datetime import datetime
print(datetime.fromtimestamp(1480232552192/1000.0))

実行結果

$ python my_aws_utils.py 
2016-11-27 16:42:32.192000

requirements.txt を使って複数ライブラリをインストールする。

$ cat requirements.txt 
requests
pytz
$ sudo pip3 install -r requirements.txt  -t ./      ←(もしくはpip)
Downloading/unpacking requests (from -r requirements.txt (line 1))
  Downloading requests-2.12.1-py2.py3-none-any.whl (574kB): 574kB downloaded
Downloading/unpacking pytz (from -r requirements.txt (line 2))
  Downloading pytz-2016.7-py2.py3-none-any.whl (480kB): 480kB downloaded
Installing collected packages: requests, pytz
Successfully installed requests pytz
Cleaning up...
$ ls -lrt
合計 80
.....
-rw-r--r-- 1 pi   pi     14 11月 21 23:56 requirements.txt
drwxr-xr-x 4 root root 4096 11月 21 23:57 requests
drwxr-xr-x 2 root root 4096 11月 21 23:57 requests-2.12.1.dist-info
drwxr-xr-x 4 root root 4096 11月 21 23:57 pytz
drwxr-xr-x 2 root root 4096 11月 21 23:57 pytz-2016.7.dist-info
$ 

ちなみに awsにアップするzipを作る際は、このディレクトリに移動して

$ zip -r xxx.zip ./*

でよいと思います。

添え字付きの for 文の文法

returnList = []
codes = createCityCodes()  ← 配列がふたつあったばあい、
names = createCityNames()  ← こちらはnames[i]とかでアクセスしたい。。

for i,code in enumerate(codes):
  returnObj = {
    'cityCode': code,
    'cityName': names[i]
  }
  returnList.append(returnObj)

みたいな感じに扱える。もしくは、

import itertools
.....
for code,name in itertools.zip_longest(codes,names):
  returnObj = {
    'cityCode': code,
    'cityName': name
  }
  returnList.append(returnObj)

こんな感じで、複数の配列をおなじfor文で回すことも可能*2。。。

改行をそのまま文字列であつかいたい

「"""」や「'''」で始めて終わることで、その間の文字列はそのまま扱われるようになります。

	text1 ="""1行目
	2行目
	3行目"""

	text2 ="""1行目
2行目
3行目"""

	print ("----")
	print (text1)
	print ("----")
	print (text2)
	print ("----")

結果は

----
1行目
	2行目
	3行目
----
1行目
2行目
3行目
----

このとおり。文字列内の改行はそのまま改行と解釈され、さらにインデントもそのままタブとして反映されるということですね。ちなみに、複数行コメントを書く際にこれを使って書いているコードもありました。

'''
/*
 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   .....
*/
'''

こんな感じで。なるほどね。。

finallyがよばれない??

Linux上で、sudo kill した場合、try/finallyのfinallyがよばれないっぽい。フォアグラウンドで実行してctrl+cした場合は問題ないのですが。。

import sys,signalしといて

def cleanup(*args):
    sys.exit(0)
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)

とか書いておくと、よばれるようになりますが、コレでいいのかな。。。

他ファイルのメソッド呼び出し

myutils.py に定義された

def cleanup(xx):

などのメソッドを呼び出すには、呼び出し側で

from myutils import cleanup,sysout

と宣言しておけば、

cleanup("hoge")

などと直接呼び出せる。

public static void main ぽく書きたい

PythonにはJavaでいう

public static void main(String[] args){
  ...
}

みたいな概念がなく、

sudo python3 xxx.py

と呼び出すと、先頭から順次実行されるっぽい。

いわゆるmainメソッドを作るやり方は以下の通りです。

import sys

def main(args):
	メイン処理


if __name__ == "__main__":
	main(sys.argv)

「 __name__ 」 には、スクリプトとして直接呼び出されたときのみ*3、"__main__" と入っているらしいので、それを判定して main メソッドを呼び出すとすれば public static void main の完成です。ついでにコマンドライン引数を上記のように渡せば、引数も同様にJavaぽくあつかうことができます。あ、引数は0番目はプログラム名なので、1番目からが実際の引数です。

参考

MacでPython3

Yosemiteを使ってるとバージョンが2.7系で、、3.x系を使いたい場合。

などを参考に、Python環境を管理するツールを入れます

$ brew install pyenv
$ echo 'export PYENV_ROOT=$HOME/.pyenv' >> ~/.bash_profile
$ echo 'export PATH=$PYENV_ROOT/bin:$PATH' >> ~/.bash_profile
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile

$ pyenv install 3.5.1
なんかエラーが出たら、たいがい
$ xcode-select --install
これもしくは、
$ sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
(これはmojaveのばあい)

$ pyenv shell 3.5.1
$ python --version
Python 3.5.1
$
$ pyenv versions    <-インストールされているモノの一覧。
* system (set by /Users/xxxx/.pyenv/version)
  2.7.11
  2.7.12
  3.5.1
$

pyenvが必要かどうかフローチャート - Qiita この辺見ると、いるかどうかよく考えて、、、という流派もあるようです。。わたくしは切替方法わかんなかったのでやりましたが、自己責任で。

JSON文字列のDump

r = requests.get('https://xxx/yyy.json')
result = json.dumps(r.json(),ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ': '))
print(result)

requests は pip(かpip3)などでインストールされてる前提で。。

[Python] JSONを扱う - YoheiM .NET

関連リンク


この記事は

選択肢 投票
おもしろかった 2  
そうでもない 0  

Top / Python / TIPS集

現在のアクセス:4691


*1 ESETではじかれてたorz
*2 python2.7はメソッドがizip_longestだったりなんか違う感じかな??
*3 よするに sudo python3 xxx.py てこと

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2021-12-14 (火) 11:32:41 (863d)