#author("2021-12-14T02:32:41+00:00","","")
#topicpath
----


#contents
*** NumPyでfor文 [#y9ec1cca]

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

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


*** 配列データを追加する [#rd087b93]

 >>> 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.]])
 >>> 



*** データ列をくっつける、分割する。 [#q3d0f8de]

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.]])
 >>> 
 


*** 切り捨て除算 [#gfbf05b2]

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


***HTTP(s)リクエストで、プロキシを通す件 [#yde6d6c1]
  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設定も要チェック((ESETではじかれてたorz))。

-[[認証プロキシ環境でpythonのRequestsライブラリを使用する方法 - メモめもメモ>http://blackwhitebear.hateblo.jp/entry/2018/01/04/203558]]
-[[ssl - Python Requests throwing SSLError - Stack Overflow>https://stackoverflow.com/questions/10667960/python-requests-throwing-sslerror]]






*** 複数の戻り値を返す件。 [#m889e777]
[[Pythonの関数で複数の戻り値を返す方法 | note.nkmk.me>https://note.nkmk.me/python-function-return-multiple-values/]]

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

*** クラスのメンバ変数にはアンスコを二つつける件 [#s422fb4c]
[[9. クラス ― Python 2.7.14 ドキュメント>https://docs.python.jp/2/tutorial/classes.html#private-variables-and-class-local-references]]



***printf の書式設定 [#a5040a3d]

 printf("Switchの状態:{0}".format(isClick)) #formatの第一引き数を表示
 printf("Counter: [{0:3.1f}]".format(counter/interval)) # 全体で3桁、小数点1桁
って感じに文字列のformat関数というのでフォーマット可能。


[[Python3におけるformat形式を自分のためにまとめてみた件 - どこかに向かうらしい話>http://hiroto1979.hatenablog.jp/entry/2016/04/01/014112]]



***Pythonでsubstring [#o419a869]
 key = 'temperature_130010.json'
 city_code = key[len('temperature_'):-5]
 -> 130010



*** 設定ファイルをあつかう [#w677f138]
[[設定ファイル (ConfigParser) - Python入門から応用までの学習サイト>http://www.python-izm.com/contents/application/config.shtml]]

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

*** Javaのlongの日付をあつかう [#te897e89]
 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 を使って複数ライブラリをインストールする。 [#va5147e7]
 $ 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 ./*
でよいと思います。

-[[Python Tips:ライブラリをまとめてインストールしたい - Life with Python>http://www.lifewithpython.com/2014/03/python-install-multiple-modules-.html]]


*** 添え字付きの for 文の文法 [#ze54935d]

 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文で回すことも可能((python2.7はメソッドがizip_longestだったりなんか違う感じかな??))。。。







***改行をそのまま文字列であつかいたい [#te4d69fb]
「"""」や「'''」で始めて終わることで、その間の文字列はそのまま扱われるようになります。

 	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がよばれない?? [#zbe6d819]
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)

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


***他ファイルのメソッド呼び出し [#jb7fd7e3]
myutils.py に定義された 
 def cleanup(xx):
などのメソッドを呼び出すには、呼び出し側で
 from myutils import cleanup,sysout
と宣言しておけば、
 cleanup("hoge")
などと直接呼び出せる。


***public static void main ぽく書きたい [#df1b09f6]

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

参考
-[[基本構文 - Python入門から応用までの学習サイト>http://www.python-izm.com/contents/introduction/syntax.shtml#a004]]


***MacでPython3 [#c8efcb87]
Yosemiteを使ってるとバージョンが2.7系で、、3.x系を使いたい場合。
-[[pyenvとvirtualenvで環境構築 - Qiita>http://qiita.com/Kodaira_/items/feadfef9add468e3a85b]]
-[[OSXでpyenvインストールメモ - Qiita>http://qiita.com/ryurock/items/c4065da9f16c1f6248b7]]

などを参考に、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>http://qiita.com/shibukawa/items/0daab479a2fd2cb8a0e7]] この辺見ると、いるかどうかよく考えて、、、という流派もあるようです。。わたくしは切替方法わかんなかったのでやりましたが、自己責任で。


***JSON文字列のDump [#s2abf34e]
 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>http://www.yoheim.net/blog.php?q=20150901]]



**関連リンク [#ke758226]
-[[[Python] 何度も調べてしまうリスト操作をまとめてみた - YoheiM .NET>http://www.yoheim.net/blog.php?q=20150801]]
-[[Python Tips:ライブラリをまとめてインストールしたい - Life with Python>http://www.lifewithpython.com/2014/03/python-install-multiple-modules-.html]]
-[[Python の datetime オブジェクトと Unix 時間の相互変換方法のまとめ &#8211; ymyzk’s blog>https://blog.ymyzk.com/2015/04/python-datetime-unix-time/]]
-[[Python 3 で少しだけ便利になった datetime の新機能 - Qiita>http://qiita.com/methane/items/d7ac3c9af5a2c659bc51]]


----
この記事は
#vote(おもしろかった,そうでもない)
#vote(おもしろかった[2],そうでもない[0])

#comment

#topicpath

SIZE(10){現在のアクセス:&counter;}


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS