邮编还是用R枚举? [英] Zip or enumerate in R?
问题描述
这些Python列表推导的R等效项是什么:
What are the R equivalents for these Python list comprehensions:
[(i,j) for i,j in zip(index, Values)]
[(i,j) for i,j in enumerate(Values)]
[(i,j) for i,j in enumerate(range(10,20))] %MWE, indexing or enumerating to
%keep up with the index, there may
%be some parameter to look this up
带有输出的示例
>>> [(i,j) for i,j in enumerate(range(10,20))]
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]
我已经用R中的一些技巧解决了这个问题,但是已经不记得了,第一个想法是itertools -pkg,但是我希望找到一种更惯用的做事方式.
I have solved this problem earlier with some trick in R but cannot remember anymore, the first idea was itertools -pkg but I am hoping to find a more idiomatic way of doing things.
推荐答案
Python enumerate
的答案:
Answer for python enumerate
:
在R中,列表是有序的(请参见此答案 ).因此,您只需要索引键(使用names()[i]
)或值(使用[[i]]
).
In R, a list is ordered (see this answer). Thus, all you need is to index either keys (using names()[i]
) or values (using [[i]]
).
使用seq_along
(或者可以做for(i in 1:length(mylist)){...}
):
> mylist <- list('a'=10,'b'=20,'c'=30)
> for (i in seq_along(mylist)){
+ print(paste(i,names(mylist)[i],mylist[[i]]))
+ }
[1] "1 a 10"
[1] "2 b 20"
[1] "3 c 30"
python zip
的答案:
Answer for python zip
:
请参阅上述答案之一,以模仿元组列表.我更喜欢BondedDust的答案所示的数据框:
See one of the above answers to mimic the list of tuples. My preference is towards a data frame as shown in BondedDust's answer:
> x <- 1:3
> y <- 4:6
> data.frame(x=x, y=y)
x y
1 1 4
2 2 5
3 3 6
这篇关于邮编还是用R枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!