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 で、凡例を表示する位置を変更する方法

凡例(legend)の表示位置を変更するには、axis の legend の loc を設定する。 次のリンクhttps://matplotlib.org/stable/api/_as_gen/mat …

no image

matplotlib で、縦横の線(グリッド)を描く方法

pyplot grid で縦横線(罫線のようなもの)を引くことができる。 例 from matplotlib import pyplot as plt data_x = [25,26,27] …

no image

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

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

no image

pythonで配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。

リストを iter に変えたあと、… next() を使う。 参考リンク https://www.programiz.com/python-programming/methods/buil …

no image

python3 で、リストを pop したものの返り値

リストを pop すると、 pop された値が返される。 例 plant_1 = [’pumpkin’, ‘ginger’, ‘potato’] plant_2 = [] print( …