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 で、ヒストグラムを作成する方法

ヒストグラムを描くには、data_hist を使う。 ヒストグラムの縦棒の数は bins で指定する。 例 from matplotlib import pyplot as plt data_hist …

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

matplotlib でcsv ファイルを読み込むとき、最初の行をスキップする方法

numpy の loadtxt で読み込む行を省略したい場合 スキップしたい行を # 等の記号でコメントアウトして、 loadtxt の comments = ‘#’ とすると …

no image

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

next() を使う。 例 my_arr = [‘春’,’夏’,’秋’,’冬’] my_iter = iter(my_arr) print(next(my_iter,’なし’)) print(next …