0
1

More than 3 years have passed since last update.

Python3のプログラミング関数 個人的まとめ

Posted at

初めに

これは、競技プログラミングなどで使用するPython3のライブラリや関数の個人的な備忘録です。

順になっているリスト

# startからendまでのリスト
# [1,...,100]が欲しいなら、start=1,end=100
li = list(range(start,end+1,step))

リストの要素を反転

li.reverse()
# または
li[::-1]

リスト内の要素の合計

sum(li)

リストをソート

# 元のリスト昇順をソート
li.sort()
# 降順
li.sort(reverse=True)

# リストを昇順にソートしたリストを返す(元のリストは変更されない)
li_2 = sorted(li)
# 降順
li_2 = sorted(li,reverse=True)

自作の比較関数でリストをソート

from functools import cmp_to_key

# 降順ソート
def comp(x,y):
    if x >= y:
        # 入れ替えなくていいなら、-1を返す
        return -1 # 降順に並べたい時に、x >= y の順番ならば、そのままでいいので、-1を返す
    else:
        # 入れ替えたいなら、1を返す
        return 1 # 昇順に並べたい時に、 x < y の順番ならば、入れ替えたいので、1を返す

# 比較関数にもとづいたソート
li.sort(key=cmp_to_key(comp))
0
1
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
0
1