转换R函数输出以匹配Python函数输出的格式

2024-06-02 09:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

将Python函数转换为R时,我尝试添加更多数据,同时在R中迭代使用strsplit()拆分的值。原始Python函数的返回值是一个列表列表,因此在R版本中应该是相同的(向量的向量)。Python函数是

anbaudauer = 12
planzen_list = [
                    'tomaten_6',
                    'karotten_4',
                    'paprika_7',
                    'erdbeeren_5',
                    'koriander_2',
                    'salat_3',
                    'zucchini_4',
                    'gurke_5',
                    'petersilie_2',
                    'radieschen_3'
                ]

def possible_combinations(values, target, with_replacement=True):
    def sub_combinations(index, l, r, t, w):
        if t == sum(filter(lambda i: isinstance(i, int), l)):
            r.append(l)
        elif t < sum(filter(lambda i: isinstance(i, int), l)):
            return
        for u in range(index, len(values)):
            sub_combinations(u if w else (u + 1), l + [values[u].split('_')[0], int(values[u].split('_')[1])], r, t, w)
        return r
    return sub_combinations(0, [], [], target, with_replacement)

raw_combinations = possible_combinations(planzen_list, anbaudauer)

# returns [['tomaten', 6, 'tomaten', 6], ['tomaten', 6, 'karotten', 4, 'koriander', 2], ['tomaten', 6, 'karotten', 4, 'petersilie', 2], ...]

R函数的当前状态为

w <- c(
  'tomaten_6',
  'karotten_4',
  'paprika_7',
  'erdbeeren_5',
  'koriander_2',
  'salat_3',
  'zucchini_4',
  'gurke_5',
  'petersilie_2',
  'radieschen_3'
)
n <- length(w)
t <- 12
D <- list()
for (j in 0:n) D[[paste(0, j)]] <- list(c())
for (i in 1:t) D[[paste(i, 0)]] <- list()
for (j in 1:n) {
  for (i in 1:t) {
    D[[paste(i, j)]] <- do.call(c, lapply(0:floor(i/as.numeric(strsplit(w[j], '_')[[1]][2])), function(r) {
      lapply(D[[paste(i-r*as.numeric(strsplit(w[j], '_')[[1]][2]), j-1)]], function(x) c(x, rep(strsplit(w[j], '_')[[1]][1]), r))
    }))
  }
}
D[[paste(t, n)]]

as.numeric(strsplit(w[j], '_')[[1]][2])我想在编号前加上蔬菜的名称。本质上,R函数应该返回与Python函数相同的结果。到目前为止,转换R函数返回值是一件棘手的事情。基本上,我试着把所有的东西拆开,然后再缝合起来。由于我已经很长时间没有使用R了,我确信有一种方便的方法可以获得与Python函数相同的返回数据


Tags: 函数inforreturnaslistintpaste
1条回答
网友
1楼 · 发布于 2024-06-02 09:04:02

为什么不在这里用上好的老调呢?首先:

#first drop the text before the '_' 
w_int <- as.integer(gsub(pattern = ".*_", replacement = "", w))
#repeat the replacement for the numbers at the end to get the vegetable names
w_names <- gsub(pattern = '_[0-9]*$', "", w)
#assign the vegetable names to the Anbaudauer-vector as names 
names(w_int) <- w_names 
w_int
tomaten   karotten    paprika  erdbeeren  koriander      salat ...
     6          4          7          5          2          3 ...
Anbaudauer <- 12

从那以后,只需检查所有加起来的组合就可以了。可能是这样的combinations of numbers to reach a given sum - recursive implementation in R我不想在这里重复

相关问题 更多 >