2
3

More than 3 years have passed since last update.

Python基本文法note(2)

Last updated at Posted at 2020-12-06

初めに

pythonを勉強中のメモです
色々今後追加していきます

モジュールとパッケージ

コマンドライン引数

import sys

print(sys.argv)

Import文とAS

モジュールからImportするのが良い

#書き方1
import lesson_package.utils

r = lesson_package.utils.say_twice('hello')
print(r)
#書き方2
from lesson_package import utils

r = utils.say_twice('hello')
print(r)
#書き方3(これはわかりづらいのであまり推奨されていない)
from lesson_package.utils import say_twice

r = say_twice('hello')
print(r)

#asも使えるが推奨されていない
from lesson_package import utils as U

絶対パスと相対パスのImport

#絶対パス
from lesson_package.tools import utils
#相対パス(あまり推奨されていない)
from ..tools import utils

アスタリスクのインポートとinit.pyとallの意味

#__int___.pyのファイルに読み込む記述をする

__all__ = ['animal']

#ディレクトリにあるファイルを読み込む(あまり勧められてない)
from lesson_package.talk import *

ImportErrorの使い所

try:
    from lesson_package import utils
except:
    from lesson_package.tools import utils

setup.pyでパッケージ化して配布する

組み込み関数

import builtins

builtins.print()

ranking = {
    'A' : 100,
    'B' : 85,
    'C' : 95
}

print(sorted(ranking, key=ranking.get, reverse = True))
>>>['A', 'C', 'B']

標準ライブラリ

#適当な変数のなかに同じ値がいくつあるか調べるプログラム
s = "lsdkfgsdighsaaidjfglskjaadfglksjdfbgsd"

d = {}
for c in s:
    if c not in d:
        d[c] = 0
    d[c] += 1
print(d)


d = {}
for c in s:
    d.setdefault(c,0)
    d[c] += 1
print(d)

>>>{'l': 3, 's': 6, 'd': 6, 'k': 3, 'f': 4, 'g': 5, 'i': 2, 'h': 1, 'a': 4, 'j': 3, 'b': 1}
>>>{'l': 3, 's': 6, 'd': 6, 'k': 3, 'f': 4, 'g': 5, 'i': 2, 'h': 1, 'a': 4, 'j': 3, 'b': 1}

#pythonの標準ライブラリーを呼び出す
from collections import defaultdict

d = defaultdict(int)

for c in s:
    d[c] += 1
print(d)
>>>{'l': 3, 's': 6, 'd': 6, 'k': 3, 'f': 4, 'g': 5, 'i': 2, 'h': 1, 'a': 4, 'j': 3, 'b': 1}

サードパーティーのライブラリ

import tarmcolor import colored

print('text')

importする際の記述の仕方

importするものに対して一文ごとに書く
アルファベット順に記述する

#サードパーティのライブラリーを読み込む際は一行空ける
import collections
import os
import sys

import termcolor

import config

#fileを使うとどこにあるかわかる
print(collections.__file__)
print(os.__file__)

#pathを見たい場合
print(sys.path)

namemain


print(__name__)
>>>__main__


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