在for循环中将两个整数添加到列表的每个元素 [英] Add two integers to each element of a list in a for loop

查看:259
本文介绍了在for循环中将两个整数添加到列表的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请让我知道这个问题是否太笼统了.

please do let me know if this question is too general.

我正在尝试使用嵌套的for循环实现for循环.每次for循环运行时,它都会print两个整数值或next进入下一个迭代.

I'm trying to implement a for loop with a nested for loop. Every time the for loop runs, it will either print two integer values or next onto the next iteration.

结果,我有输出 从如下所示的for循环中:

As a result, I have outputs from the for loop that looks like this:

[1] 10 57
[1] 10 58
[1] 10 59
[1] 10 63
[1] 10 64
[1] 10 67
[1] 10 68
[1] 10 69
[1] 10 70
[1] 10 71
[1] 10 72
[1] 10 75
[1] 10 76
[1] 10 77
[1] 10 78
[1] 10 79
[1] 10 80
[1] 10 82
[1] 10 86
[1] 10 87
[1] 10 90

我想知道在列表中插入这些整数对的最佳实践是什么.由于在迭代器为j的for循环中嵌套了一个迭代器为i的for循环,所以我不能只写:

I was wondering what are best practices for inserting thse pairs of integers in lists. Since there is a for loop with an iterator of i nested inside a for loop with an iterator of j, I can not just write:

list[[i]] <- c(i, j)

推荐答案

indx是带有一些随机值的向量:

Say indx is a vector with some random values:

[1] 58 61 67 69 70 72 78 79 84 85

我要编写的for循环:

The for loop I would write:

for(i in 1:3){
  for(j in indx){
    print(c(i, j))
  }
}

将产生以下输出(不将其分配给对象):

Would produce the following output (without assigning it to an object):

[1]  1 58
[1]  1 61
[1]  1 67
[1]  1 69
[1]  1 70
[1]  1 72
[1]  1 78
[1]  1 79
[1]  1 84
[1]  1 85
[1]  2 58
[1]  2 61
...
[1]  3 84
[1]  3 85

如果您尝试将其保存到向量中,则此代码对您有用:

If you're trying to save it into a vector, this code works for you:

myls <- vector()
for(i in 1:3){
  for(j in indx){
      myls <- c(myls, c(i, j))
  }
}

编辑 基于OP的附加注释,我想向您展示另一种直接获取列表的方法,方法是将ij的每种组合附加为列表元素:

EDIT Based on OP's additional comment, I wanted to show you another way to directly get a list, by appending each combination of i and j as a list element:

indx <- c(58, 61, 67, 69, 70, 72, 78, 79, 84, 85)
myls <- list()
for(i in 1:3){
  for(j in indx){
      myls <- c(myls, list(c(i, j)))
  }
}

您的myls变量现在是列表:

myls[1:3]

[[1]]
[1]  1 58

[[2]]
[1]  1 61

[[3]]
[1]  1 67

这篇关于在for循环中将两个整数添加到列表的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆