# 如同在python中一样，在for循环中追加值

##### 问题描述投票：1回答：2

``````# Python
def square_area(side):
return side * side

results = []
for i in range(1, 10):
x = square_area(i)
results.append(x)
print results
``````

``````[1, 4, 9, 16, 25, 36, 49, 64, 81]
``````

``````# R
square_area <- function(side) {
side * side
}

results=list()
for (i in 1:10){
x <- square_area(i)
results[i] = x
}
print(results)
``````

``````[[1]]
[1] 1

[[2]]
[1] 4

[[3]]
[1] 9

[[4]]
[1] 16

[[5]]
[1] 25

[[6]]
[1] 36

[[7]]
[1] 49

[[8]]
[1] 64

[[9]]
[1] 81

[[10]]
[1] 100
``````

python r list for-loop
##### 2个回答
0

`````` (1:10)^2
#[1]   1   4   9  16  25  36  49  64  81 100
``````

`````` as.list((1:10)^2)
``````

0

Python 中的 list 和 R 中的向量是一样的，这是完全错误的。

``````[1, [2, 3.333], "I'm a string bitch!", [1, "hollymolly"]]
``````

R中的向量很像Python中的np.array。这就是为什么R很酷的原因，它不需要一个包来处理矩阵。

``````#R
Area2 <- function(side){   #This is your function
side^2
}

# The truth is that in your example, is enough to employ a vector and add stuff to it.
# That's why I will make a slightly more complex code to append shit to a list and show my point
LIST = list()

for(i in 1:2){
vect = c()
for(j in 1:10){
vect = c(vect, i * Area2(j))
}
LIST[[i]] = vect  #This is the climax of the whole story (how to append to a List)
}

print(LIST)
``````

Outcome:

``````[[1]]
[1]   1   4   9  16  25  36  49  64  81 100

[[2]]
[1]   2   8  18  32  50  72  98 128 162 200
``````