python3

python でリストに、コロン演算子2つ(::)を使う

投稿日:2020年12月23日 更新日:

リストのコロンで指定できるパラメータには、「start, end, step」という意味がある。

以下の例では、:: 5 とした場合には、5 をステップとして、次に進んでいく。

::-5 とした場合には、5 をステップとして、前に戻っていく。

print('range(100)[::-5] の結果を表示')
for i in range(100)[::-5]:
    print(i, end=' ')

print('\nrange(100)[::-5] の結果を表示')
for i in range(100)[::5]:
    print(i, end=' ')
print('\n')

結果

range(100)[::-5] の結果を表示
99 94 89 84 79 74 69 64 59 54 49 44 39 34 29 24 19 14 9 4 
range(100)[::-5] の結果を表示
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95

-python3
-,

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

matplotlib で、y軸に二種類の軸を設定する方法

y軸に、2種類のグラフを異なるスケールでプロットする。 matplotlib axes の twinx() を使う。 https://matplotlib.org/stable/api/_as_gen …

no image

python3 でクラス内からだけアクセスするメソッドを作る方法

1.メソッド内でメソッドを定義する2.メソッド最初にアンダースコアをつける(慣習)例: def _some_internal_func(self): … このうち、2.のメソッド名先頭にアンダース …

no image

matplotlib で、グラフの点の見た目を変更する方法

「marker」で指定すればよい。 次のページを参考に、plotの「marker」を変更する。 https://matplotlib.org/stable/api/markers_api.html 例 …

no image

matplotlib で、x,y の軸上の数値を表示する方法

ax の xtics と ytics を使って表示する。 詳細は次のドキュメントを参照。 https://matplotlib.org/stable/gallery/lines_bars_and_ma …

no image

python3 で、配列の配列をソートする

ラムダ式を使って、任意の要素についてソートすることができる。 例 arr = [[1,2,3],[2,1,2],[3,3,4],[4,4,1]] for i i …