LoginSignup
4
4

More than 3 years have passed since last update.

Python 基本書き方

Last updated at Posted at 2020-08-12

pythonの基本の整理のログを書きます。

データタイプ

intとfloatで計算すると、情報量の多いfloat型になる

type(3+1.3)
> float

0,1 0.0001 など小数を書くとき

1e-1
> 0.1 ( 10の-1乗 = 10分の1 = 0.1)
1e-3
>0.001

スライス

'hello'[1:3]
>el

'fileid.png'[:-4]
>fileid
'fileid.png'[-4:]
>.png

スプリット 分けてリストにする

'hello world'.split(' ')
>['hello' ,' world']

改行
\nで改行

タプル  変更できないリスト

Set ユニークな値だけを持つリスト (頻度低)
```
set1 = {1,1,1,2,2,3,3,3}

[1,2,3]
```

set()はlistの重複を取り除くときによく使う

list1 = [1,2,2,3,3,3,4,4,4,4]
set(list1)
> {1,2,3,4)

is の使い方  ( ~と~は同じである。)

#変数を比較
a = 1
b = 1
a is b
> True

#リストを比較 (リストは違うメモリの値を比較するため、別のものとして扱われる)
a = [1,2]
b = [1,2]
a is b
> False
a is not b
> True

★~ is None として、nullオブジェクトNoneno
判別に使われるケースがほとんど(データを扱うとき)

if文 一行で書くとき  ★(わかりづらいので,lambda関数以外はあまり使われない)

a = 3
print(' a is 2') if a == 2 else print('a is NOT 2')
> a is NOT 2

(順番) 最初に実行したい処理 if~ else 実行処理
※一行の場合は必ずelseが必要

リストのindexと要素をどちらも使いたい時、enumerate()を使う

for idx,color in enumerate(colors):
    favorite color = 'blue'
    if color == favorite color:
        print('{}:{} is my favorite color!'.format(idx,color))
    else:
        print('{}:{} is  not my favorite color...'.format(idx,color))

リスト内包表記 ・・ リストの中に、for文を書く (便利!) ★★

colors = ["red","blue","green",'yellow','white']
[color + '.png' for color in colors ]
> ['red.png', 'blue.png', 'green.png', 'yellow.png', 'white.png']

iterableとiterator

そのオブジェクトがイテレーション(反復処理、ループ処理)できるか判別する。

iterable(イテラブル) =反復可能な対象(オブジェクト)
○ String,List,Tuple,Set,Dict
✖️ interger, Float, Boolean

詳しい定義
iterable: iter()関数でIteratorを返すオブジェクト
iterator: next()関数でIterationできるオブジェクト

★「イテラブルかどうか?」→for文で回せる
・・・・難しくなると、イテレータを返すのかイテラブルを返すのか判別できることが重要になる。
(IteratorもIterableなもの)

関数

<基本概念 ・操作>
パラメーター(Parameter)と引数(Argument)

y = 3x (xがパラメーター  x=1の場合、1が引数)

_ (アンダースコア) 最後に実行したコードの戻り値が格納される

その関数に戻り値がない場合、Noneを返す。
ex 関数の定義にreturnが無い物

p_r = print("hello world")
p_r
>
p_r is None
>True

★デフォルト値があるパラメータをデフォルト値がないパラメータの前には置けない。
必ず、後ろに置かないといけない

def function_example( param1 = 'hello', param2):
>エラーとなる

def function_example( param1 , param2 = 'hello'):
>実行可能

★便利機能★
SHIFT + tab で関数の中身(使い方)を表示してくれる

mutableとimmutable

Mutable         vs      Immutable
変更可能なオブジェクト         変更不可なオブジェクト
list integer, stirng
dict float, bool , tuple
set

Mutable は参照渡し 値ではなく、メモリの場所を渡している
(Pythonは全て参照渡し)

Immutableなオブジェクトの場合は、値渡しのような挙動をする。

fig-05.png

b64309a1-6425-9fd7-cf63-565cbd65a549.png

何故こんなややこしい仕組みなのか??

(なぜ、 mutable ・ Immutable があるのか?)

容量が大きくなりがちなオブジェクト(list,dict)はmutable→値渡しをすると複製が行われるため、メモリの容量がすぐ一杯になってしまう。なので参照渡し

lambda関数

一行で書ける簡単な関数の場合に、わざわざ定義するまでもない無名関数として使う
表計算でよく使う

argsとkwargs

def return_only_png(*args):

    png_list = []

    for filename in args:
        if filename[-4:] == '.png':
            png_list.append(filename)

    return png_list

*argsは引数のパラメータをタプルとして使う。*argsには、いくらでも要素を入れられる。
args以外の名前でもOK

※並立処理のところで*argsをよく使う

**kwargsの場合はdictionaryで受け取る。

def print_dict(**kwargs):
    print(kwargs)

print_dict(a=1,b=2)
> {'a': 1, 'b': 2}
4
4
1

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
4
4