【问题标题】:Creating a loop, which picks up where the previous stopped创建一个循环,从前一个停止的地方开始
【发布时间】:2021-11-04 05:00:59
【问题描述】:

这个问题的原因是我需要下载有每日下载限制的数据。我正在尝试编写一个循环,从中断的地方开始下载(第二天)。

我创建了以下示例,其中我将下载功能替换为一个简单的索引 (item_list[i+amount_done]):

# data = a list, to be filled with all the downloads
data = list()

# Yesterday, I did one list item, so the amount done is 1
data[[1]] <- "1"
amount_done <- length(data)

# The list of items that need to be downloaded
item_list <- c("1", "2", "3", "4")

# The loop I created to pick up where it stopped
for (i in (1+amount_done):length(item_list)){
  data[[i+amount_done]] <- item_list[i+amount_done] # This is where the download function would be using the index as used in this example.
  print(data[[i+amount_done]])
}

不知何故,结果是这样的:

想要的结果很简单

data[[1]] 
"1"
data[[2]] 
"2"
data[[3]] 
"3"
data[[4]] 
"4"

我在这里做错了什么?

【问题讨论】:

  • 为什么不每天创建一个新列表,然后遍历整个列表呢?这样您就不必为索引而烦恼,您可以直接迭代项目,从而使代码更加简单。
  • @KonradRudolph 为什么要每天遍历整个列表?这不是在不需要的地方浪费大量资源吗?列表的某些部分昨天已经下载,我们今天需要从剩余部分开始下载。
  • @RonakShah 这就是我说“每天创建一个新列表”的原因。如果需要,这些列表显然可以在处理后合并。

标签: r list for-loop


【解决方案1】:

i 是您要在循环中使用的正确索引。

data = list()

# Yesterday, I did one list item, so the amount done is 1
data[[1]] <- "1"
amount_done <- length(data)

# The list of items that need to be downloaded
item_list <- c("1", "2", "3", "4")

# The loop I created to pick up where it stopped
for (i in (1+amount_done):length(item_list)){
  data[[i]] <- item_list[i] 
  print(data[[i]])
}

data

#[[1]]
#[1] "1"

#[[2]]
#[1] "2"

#[[3]]
#[1] "3"

#[[4]]
#[1] "4"

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2014-01-21
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多