[英]Converting Python Function into R Function
I have the following Python function,我有以下 Python 函数,
import random
import math
deck = [2,3,4,5,6,7,8,9,10,10,10,10,11]
def draw_card(deck):
card = deck.pop(random.sample(range(len(deck)), 1)[0])
return(card)
print(deck,'\n')
my_draw = draw_card(deck)
print(my_draw, '\n')
print(deck, '\n')
The output is below,输出如下,
[2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
3
[2, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
I need to convert this to R but I understand there is no equivalent Python list.pop function in R. I am not worried about random pick as I can do a rep
in R and am able to emulate the drawing of card in R by,我需要将它转换为 R,但我知道 R 中没有等效的 Python list.pop 函数。我不担心随机选择,因为我可以在 R 中做一个
rep
,并且能够模拟 R 中的卡片绘图,
DrawCard <- function(card){
card <- tail(deck,1)
return(card)
}
Also I am able remove the same drawn card by head(deck, -1)
but I do not know how to feed the 2 in 1 function like in Python that will return both the card value and also the shorter length deck.此外,我可以通过
head(deck, -1)
移除同一张抽取的卡片head(deck, -1)
但我不知道如何像在 Python 中那样提供 2 合 1 函数,该函数将返回卡片值和较短长度的卡片组。
Please help.请帮忙。
Thanks, Lobbie谢谢,洛比
With your logic, return as list
按照你的逻辑,作为
list
返回
DrawCard <- function(deck){
card <- tail(deck,1)
remain<-head(deck,9)
return(list(card,remain))
}
cc<-1:10
DrawCard(cc)
A better logic may be,更好的逻辑可能是,
DrawCard <- function(deck){
ind<-1:length(deck)
choose<-sample(ind,1)
card<-deck[choose]
remain<-deck[-choose]
return(list(card,remain))
}
Appended: to answer loop附加:回答循环
sum=0
ll<-length(cc)
deck_rem<-cc
for(x in 1:ll){
a<-DrawCard(deck_rem)
deck_rem=a[[2]]
sum=sum+a[[1]]
print(a[[1]])
print(a[[2]])
print(sum)
}
I'm not suggesting that you do this (returning a list of the card and the new deck is a better idea), but you can have the function alter the global deck
variable like so:我不是建议你这样做(返回卡片列表和新牌组是一个更好的主意),但你可以让函数改变全局
deck
变量,如下所示:
draw_card <- function(deck){
card <- tail(deck,1)
deck <<- head(deck, length(deck)-1)
return(card)
}
print(deck)
# [1] 2 3 4 5 6 7 8 9 10 10 10 10 11
print(draw_card(deck))
# [1] 11
print(deck)
# [1] 2 3 4 5 6 7 8 9 10 10 10 10
For random sampling (thanks to Ben Bolker) and a function that will work with any deck variable:对于随机抽样(感谢 Ben Bolker)和一个适用于任何甲板变量的函数:
draw_card <- function(deck){
s <- sample(length(deck),size=1)
card <- deck[s]
n <- deparse(substitute(deck))
assign(n, deck[-s], envir=globalenv())
return(card)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.