制作递归列表的好方法是什么?

时间:2016-02-01 19:58:38

标签: r list

我们说,我有3个数字:20,10,5len=5

我想列出一个:

20
10
5
20 20
20 10
20 5
10 20
10 10
10 5
5 20
5 10
5 5
20 20 20
20 20 10
20 20 5
20 10 20
..
20 20 20 20 20
..
5 5 5 5 5

但是我不确定如何以一种好的方式制作这种列表(无论编程语言如何,但R更喜欢)?

你能给我一个提示吗?

3 个答案:

答案 0 :(得分:3)

这有效:

x <- c(20, 10, 5)
len <- 5
rl <- sapply(1:len, function(n) expand.grid(list(x)[rep(1, n)]))

此处rl是一个长度为len的列表,其中,例如,

rl[[2]]
#   Var1 Var2
# 1   20   20
# 2   10   20
# 3    5   20
# 4   20   10
# 5   10   10
# 6    5   10
# 7   20    5
# 8   10    5
# 9    5    5

答案 1 :(得分:1)

Python解决方案:

from itertools import combinations_with_replacement

l = 5 #len is a reserved keyword in Python

for i in range(1, l+1):
    print(list(combinations_with_replacement([20, 10, 5], i)))

结果

[(20,), (10,), (5,)] [(20, 20), (20, 10), (20, 5), (10, 10), (10, 5), (5, 5)] [(20, 20, 20), (20, 20, 10), (20, 20, 5), (20, 10, 10), (20, 10, 5)

由于它的长度,我缩短了输出,但你明白了。

答案 2 :(得分:0)

我想为R添加一个答案:

library (gtools)
permutations (n = length (c(20,10,5)), r = 5, v = c(20,10,5), repeats.allowed=TRUE)