4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonコーティングテクニックメモ

Last updated at Posted at 2022-02-21

他のプログラミング言語の経験者がちょっとだけPythonの知識を学んで、コーティングを始めると漏れやすい便利なテクニックをちょちょいまとめました。

memo.py
#変数の値交換
x,y = 1,2
y,x = x,y
print(x,y) #2 1

#リスト内の全項目と比較
z = 0
print(z in [x,y]) #False
print(z not in [x,y]) #True

#for文やif文でリストを定義する
list = [i for i in range(3,10) if i%2 == 0]
print(list) #[4, 6, 8]

#リストの項目数と同じ数の変数にまとめて値を代入する
str_list = ["a","b","c"]
a,b,c = str_list
print(a,b,c) #a b c

#リスト合併
str_list = [*str_list,*["d","e"]]
print(str_list) #['a', 'b', 'c', 'd', 'e']

#リストの項目の値を変数と可変長引数に代入
s,*l = str_list 
print(l) #['b', 'c', 'd', 'e']

#リスト→文字列
str = "".join(str_list)
print(str) #abcde

#for文で辞書を定義する
dict = {i:i.upper() for i in str_list}
print(dict) #{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}

#辞書合併
dict = {**dict, **{"f":"F","g":"G"}}
print(dict) #{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G'}

#リスト項目增殖
flg_list = [False]*5
print(flg_list) #[False, False, False, False, False]

test = [-25,3,11,11]
#リストの中の絶対値が一番小さい項目を特定
print(min(set(test), key = abs)) #3
#リストの中の数一番多い項目を特定
print(max(set(test), key = test.count)) #11
#リストの全項目と比較し、いずれの結果がTrueの場合、Trueとする
print(any(i == 11 for i in test)) #True
#リストの全項目と比較し、いずれの結果がFalseの場合、Falseとする
print(all(i == 11 for i in test)) #False

#複数のfor文をまとめて処理する
from itertools import product
tuple_i = (5,6)
tuple_j = (3,4)
tuple_k = (1,2)
print([i*j+k for i,j,k in product(tuple_i,tuple_j,tuple_k)]) #[16, 17, 21, 22, 19, 20, 25, 26]

#CounterモジュールでCounter用辞書を生成する
from collections import Counter
item_list = ["回復薬","回復薬","ハチミツ","ハチミツ","ハチミツ","回復薬グレード"]
item_counter = Counter(item_list)
print(item_counter) #Counter({'ハチミツ': 3, '回復薬': 2, '回復薬グレード': 1})
print(item_counter["ハチミツ"]) #3
print(Counter("abbcccdddd")) #Counter({'d': 4, 'c': 3, 'b': 2, 'a': 1})

#jsonファイル作成
import json
pokemon_data = {"Name":"Garchomp","No":"445","Type1":"Dragon","Type2":"Ground",
"Stats":{"HP":108,"Atk":130,"Def":95,"Sp.Atk":80,"Sp.Def":85,"Speed":102}}
print(json.dumps(pokemon_data, indent=2)) #インデント設置
#実行結果↓
'''
{
  "Name": "Garchomp",
  "No": "445",
  "Type1": "Dragon",
  "Type2": "Ground",
  "Stats": {
    "HP": 108,
    "Atk": 130,
    "Def": 95,
    "Sp.Atk": 80,
    "Sp.Def": 85,
    "Speed": 102
  }
}
'''
#再帰の書き方(階乗)
def factorial(n):
    return 1 if n == 1 else n*factorial(n-1)
    
print(factorial(4)) #24
4
5
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
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?