Urchin_learningのPython勉強ブログ

ふと思い立ってPythonを勉強しようと思い立ちました。その勉強日記。

Python 勉強2日目 配列 tuple / list / dict / set

Python 勉強2日目 配列

1.tuple

上が書いたコード

下が返された値

import datetime

def get_today():

    today = datetime.datetime.today()
    value = (today.year,today.month,today.day)

    return value

test_tuple = get_today()

print(test_tuple)
print(test_tuple[0])
print(test_tuple[1])
print(test_tuple[2])

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(2021, 5, 8)
2021
5
8

後から他の要素を足したり、要素を消したりは出来ない。

 

2.list

上が書いたコード

下が返された値

#tupleは()で囲う、listはで囲う
test_list = ["urchin","-","izm",".","com"]
print(test_list)

print("--------------------------")

for i in test_list:
    print(i)

test_list2 = 
print(test_list2)

print("-----------------")

#appendは末尾への追加
test_list2.append("Urchin")
test_list2.append("-")
test_list2.append("izm")
test_list2.append("-")
test_list2.append("com")

#insertは入れる位置を指定できる
print(test_list2)
print("------------------------------")
test_list2.insert(0,"http://WWW.")
test_list2.insert(7,"/details")

print(test_list2)

print("------------------------------")

#popは指定した位置の要素を削除し、削除した要素を返す
#指定しないと末尾を消す。
print(test_list2)
print(test_list2.pop(0))
print(test_list2.pop())
print(test_list2)

#indexはある要素がlist内の最初に見つかった位置を返してくれる
print(test_list2.index("-"))

#countは指定の要素がlist内でいくつあるかを数えて返してくれる
test_list3 = ["1","0","3","1","1","2"]
print(test_list3.count("1"))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

['urchin', '-', 'izm', '.', 'com']
--------------------------
urchin
-
izm
.
com
[]
-----------------
['Urchin', '-', 'izm', '-', 'com']
------------------------------
['http://WWW.', 'Urchin', '-', 'izm', '-', 'com', '/details']
------------------------------
['http://WWW.', 'Urchin', '-', 'izm', '-', 'com', '/details']
http://WWW.
/details
['Urchin', '-', 'izm', '-', 'com']
1
3

 

3.dict (ディクショナリ)

上が書いたコード

下が返された値

#dictは{}で包んで"key":"value"の形でセット化して書いていく
test_dict1 = {"青":"blue","赤":"red","黄":"yellow","緑":"green"}
print(test_dict1)

print("----------------------------------")

for i in test_dict1:
    print(i)
    print(test_dict1[i])
    print("------------------------")

#getを使えばkeyとセットのvalueを返してくれる
#getはそのkeyが無くてもエラーにならない

print("----------------------------------")
print(test_dict1)

print(test_dict1.get("赤"))
print(test_dict1.get("蒼"))
print(test_dict1.get("翠","this video has been deleted" ))
print("----------------------------------")
#dict_obj["key"] = ""で要素を追加できる
test_dict1["紫"] = "purple"
test_dict1["白"] = "white"
test_dict1["黒"] = "black"
print(test_dict1)
print("----------------------------------")
#delで要素を削除できる
del test_dict1["紫"]
print(test_dict1)
print("----------------------------------")
#keys や valuesはkey or valueのみをlist化して返してくれる
print(test_dict1.keys())
print(test_dict1.values())

#itemsはkeyとvalueを同時に取得してくれる
print("----------------------------------")

for keyvalue in test_dict1.items():
    print(keyvalue)

#inで指定のkeyを保持しているかT/Fで判定してくれる

print("赤" in test_dict1)
print("茶" in test_dict1)
print("blue" in test_dict1#valueで保持しててもfalse

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

{'青': 'blue', '赤': 'red', '黄': 'yellow', '緑': 'green'}
----------------------------------

blue
------------------------

red
------------------------

yellow
------------------------

green
------------------------
----------------------------------
{'青': 'blue', '赤': 'red', '黄': 'yellow', '緑': 'green'}
red
None
this video has been deleted
----------------------------------
{'青': 'blue', '赤': 'red', '黄': 'yellow', '緑': 'green', '紫': 'purple', '白': 'white', '黒': 'black'}
----------------------------------
{'青': 'blue', '赤': 'red', '黄': 'yellow', '緑': 'green', '白': 'white', '黒': 'black'}----------------------------------
dict_keys(['青', '赤', '黄', '緑', '白', '黒'])
dict_values(['blue', 'red', 'yellow', 'green', 'white', 'black'])
----------------------------------
青 blue
赤 red
黄 yellow
緑 green
白 white
黒 black
True
False
False

 

4.set

上が書いたコード

下が返された値

#setもdict同様{}で囲うよ
#setは重複した要素は持てないよ
test_set ={"red","blue","yellow","red"}
print(test_set)
for i in test_set:
    print(i)

print("-------------------------")

#空のsetを作るには test_obj = set()というようにする
#dictは dict_obj = {}でよかったのに
test_set2 = set()

#単一要素の追加はadd 、複数はupdate
test_set2.add("red")
print(test_set2)
test_set2.update({"blue","yellow","green","balck","white"})
print(test_set2#追加の順番はランダムみたい

#削除はremove,discard removeは指定した要素がないとエラーになる
test_set2.remove("red")
print(test_set2)
test_set2.discard("blue")
print(test_set2)

#frozensetはadd,update,remove,discardなどの追加/削除を使うとエラー

test_set3 = frozenset({"赤","青","黄"})
print(test_set3)
test_set3.add("黒")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

{'red', 'blue', 'yellow'}
red
blue
yellow
-------------------------
{'red'}
{'red', 'blue', 'green', 'white', 'balck', 'yellow'}
{'blue', 'green', 'white', 'balck', 'yellow'}
{'green', 'white', 'balck', 'yellow'}
frozenset({'赤', '黄', '青'})
Traceback (most recent call last):
File "c:\Users\nhiro\Desktop\Python-Practice\Urchin07.py", line 30, in <module>
test_set3.add("黒")
AttributeError: 'frozenset' object has no attribute 'add'

 

色々試しながら書いてたけど、listではできてdictではできないとかがあってややこしい。。

 

お次はスライス

 

Python 勉強1日目 数字の扱い方

Pytyhon勉強1日目

1.数字の扱い方

上は書いたコード

下は返された値

 
# + - * /の使い方はまぁEXCELと一緒
test_integer = 100
print(test_integer +10)
print(test_integer -10)
print(test_integer *10)
print(test_integer /10)

#文字列で書いた数字はint()で数値に変えれる (integer=訳:整数)
test_str = "100"
print(int(test_str) +100.5)

#int()は整数に対して float()は小数点がついた文字列を数値に変換できる
test_str2 = "100.5"
print(float(test_str2) +100)

#j or Jを付けると虚数扱い complex=複素数 real part=実部 imagenary part=虚部
test_complex = 100 + 10J
print(test_complex)
print(test_complex.real)
print(test_complex.imag) 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

f:id:Urchin_learning:20210505132355p:plain

複素数とか遠い過去の記憶で、改めて調べました。

虚数とは何か?複素数とは何か?が一気に分かりやすくなる記事|アタリマエ!

2.日付・時間

上は書いたコード

下は返された値

#特定のライブラリを使うにはimport ##
import datetime

today = datetime .date .today()
todaydetail = datetime .datetime .today()

#今日の日付
print("---------------------------")
print(today)
print(todaydetail)

#今日の日付 それぞれの値の取り方
print("---------------------------")
print(today .year)
print(today .month)
print(today .day)
print(todaydetail .hour)
print(todaydetail .minute)
print(todaydetail .second)
print(todaydetail .microsecond)

#日付のフォーマット #isoformatはY-M-Dで表示してくれる
print("---------------------------")
print(today.isoformat())  #isiformat()はY-M-Dで書いてくれる
print(todaydetail.strftime("%Y/%m/%d %H:%M:%S")) #なんでか分かんないけど%じゃないとエラー

#明日の日付
print("---------------------------")
print(today + datetime.timedelta(days=2))

#2021年5月5日 +10日
may5 = datetime.datetime(2021,5,5)
print(may5 + datetime.timedelta(days=10))

#1995/7/9から今日までの日数
birthday = datetime.date(1995,7,9)
calc = today - birthday
print(calc.days)

#うるう年 isleapはうるう年があるかないかをT/F判定 leapdaysは指定期間に何回うるう年があったか
import calendar
print(calendar.isleap(2011))
print(calendar.isleap(2012))
print(calendar.isleap(2013))

print(calendar.leapdays(1996,2021))

#生まれてからの日数(うるう年抜き)
print(int(calendar.leapdays(1996,2021)))
birthdays = calc.days - calendar.leapdays(1996,2021)
print(birthdays)

#↑なんかうるう年引かなきゃって思ったけど
#ちゃんとcalc = today - birthdayで引かれてるからいらなかったね

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

f:id:Urchin_learning:20210505142541p:plain

年齢がバレますね。

次は配列・連想配列...??

 
 

Python 勉強1日目 勉強開始~インストール~VScodeの使い方~文字列の扱い方

全くのプログラミング初心者であるUrchinがPythonを勉強してみます。

なにか勉強してみようと思いプログラミングに行きつきました。

大学時代にウニ(Urchin)を研究していたのでハンドルネームはUrchinです。

会社ではExcelくらいしか触らないのですが、アナログな部分がかなり多い会社なのでこのプログラミングが何かに生かせればと思っています。 

0.勉強開始

参考にするのは以下。

基本的な部分をPython‐izmの流れで勉強し、そのあと入門 Python3の内容に挑もうと思います。

勉強の仕方間違ってたら教えてほしいです。。

 

Python‐izm

www.python-izm.com

 

・入門 Python3

www.amazon.co.jp

 

1.インストール

 下記URLからWindows版のインストーラをダウンロードして、実行。

https://code.visualstudio.com/

インストールが完了したら実行して、

左側のバーから下記3つの拡張機能を検索してインストール

Python

・Japanese Language Pack for Visual Studio Code

・Pylance

 

2.VS codeの使いかた

左のバーの一番上のエクスプローラーで「新しいファイル」を作成

※Urchinは勉強用のフォルダをデスクトップに設置。

 今後はその中にPython File (.py)が格納される。

 

3.文字列の扱い方

上が書いたコード

下が返された値

# 文字列の入力方法
#'' or "" or """(改行するとき)で括ると文字列になる
print('Urchin-izm')
print('Urchin-izm2')
test_str = """
Urchin1
  Urchin2
"""
print(test_str)

#作った文字列に対して +や+= でさらに文字列をくっ付ける
test_str2 = "urchin"
test_str3 = test_str2 + "-"
test_str3 += "izm"

print(test_str3)

#掛け算だと繰り返してくれる
test_str4 = test_str3 * 2

#replace("A","B")で文字列の中の"A"→"B"に書き換えれる
print(test_str4 .replace('izm','ism'))

#split("A")でAも文字でlistに分けることができる
print(test_str3 .split("-"))

#rjust(A,"B")でTotalの文字数がA(数字)分になるように"B"を左側に埋め込む
test_str5 = "0123"
print(test_str5 .rjust(20,"-"))
#ljustは右に埋め込むと思う

#zfill(A) でTotalの文字数がA(数字)分になるように左に0を埋め込む
print(test_str5 .zfill(20))

#startswith("A"),endswith("A")で始まりor終わりが"A"になっているかをT/Fで返す
print(test_str3 .startswith("urchin"))
print(test_str3 .startswith("izm"))
print(test_str3 .endswith("uchin"))
print(test_str3 .endswith("izm"))

#upper("A"),lower("A")は"A"を大文字・小文字化してくれる
test_str6 = "abcdefg"
test_str7 = "HIJKLMN"
print(test_str6 .upper())
print(test_str7 .lower())

#lstrip("A"),rstrip("A")で左or右から"A"を除去 Aを入れなければ空白を消す
test_str8 = "   abc  def  ghi  jkl   "
test_str8 = test_str8 .rstrip()
print(test_str8)
test_str8 = test_str8.lstrip()
print(test_str8)
test_str8 = test_str8.lstrip("abc")
print(test_str8)
test_str8 = test_str8.rstrip("jkl")
print(test_str8)
test_str8 = test_str8.strip()
print(test_str8)
test_str8 = test_str8.strip("def")
print(test_str8)
test_str8 = test_str8.rstrip()
print(test_str8)
test_str8 = test_str8.rstrip("i")
print(test_str8)
test_str8 = test_str8.lstrip("  g")
print(test_str8)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

f:id:Urchin_learning:20210505114800p:plain

このへんは問題なく理解できた。と思う。

次は数字の扱い方。