Skip to content

Instantly share code, notes, and snippets.

@lusingander
Created April 3, 2019 02:55
Show Gist options
  • Save lusingander/bbec71f807e256031504d90723f9d372 to your computer and use it in GitHub Desktop.
Save lusingander/bbec71f807e256031504d90723f9d372 to your computer and use it in GitHub Desktop.
Python3 のショートコーディングに関する Tips

Python3 Short Coding Tips

Yes/No 出力

"YNeos"[cond::2]
# => "No" if cond else "Yes"
"NYoe s"[cond::2]
# => "Yes" if cond else "No"

条件演算子

[a,b][cond]
# => b if cond else a

+1, -1

a = 3
b = 4
~-a*~-b
# => 6 (2 * 3)
-~a*-~b
# => 20 (4 * 5)
# 括弧を省略可能

関数名短縮

# 別名
i=input
i()

# 三回以上呼ぶ場合短縮になる
input();input();input()
i=input;i();i();i();

# lambda
i=lambda:int(input())
i()

# 三回以上呼ぶ場合短縮になる
int(input());int(input());int(input());
i=lambda:int(input());i();i();i();

map

# NG
# Python3 の map はジェネレータなので再利用できない
a=map(int,input().split());print(max(a),min(a))
# OK リスト等に変換
a=list(map(int,input().split()));print(max(a),min(a))
# OK
*a,b=sorted(map(int,input().split()));print(b,min(a))
# OK
a,*b,c=sorted(map(int,input().split()));print(c,a)
# OK 一括で受けたいなら , をつける
*a,=map(int,input().split());print(max(a),min(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment