1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonとRの制御構造(for)

Last updated at Posted at 2019-03-04
RとPythonの制御構造(for)

 いろいろなスクリプトを書いているとこの処理系はどういう制御構造だったかな?と迷うことがあります。まずはforループについて記述してみました。
 Python等のループは機能豊富で描ききれていないところも多くあります。今後少しづつ書き込んでいきたいと考えます。
 

ループ(for) Python

for i in range(10):
  print(i)

Pythonの特徴として、字下げで一つのブロックを表すことです。他の処理系出身者が間違えやすいのが

for i in 10:
  print(i)

と記述してしまうことです。
その理由は考え方の違いです。

Pythonの考え方
range(10):

の意味は、0〜9の配列(リスト)を作りなさいという意味です。1〜10出ないことに注意してください。

 そのため、次のようなこともできます。

char1 = 'test'
for char2 in char1:
  print(char2)
  
char3 = ['test1','test2','test3']
for char4 in char3:
  print(char4)
t
e
s
t
test1
test2
test3

ループ(for) R

for(i in 1:10){
  print(i)
}

 RもPythonと同じような考え方です。明示的に1〜10を指定します。
forの対象となるのは{}の内部です。見やすくなるようにインテンドしていますが、Pythonと異なり、インデントに意味はありません。

PythonとRに共通するのは、最初に配列を作ってから、それに対してループを行うことです。

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?