提问人:FB001 提问时间:8/5/2023 最后编辑:FB001 更新时间:8/5/2023 访问量:55
使用 %in% 与列表进行匹配
Matching against a list using %in%
问:
我正在编写一个可以用来玩“石头、纸、剪刀、蜥蜴、斯波克”的函数。我曾经要求用户选择一个选项,给计算机一个选项,并定义如果两个选项匹配 10 个获胜对中的一个,就会发生胜利。代码有效(如,不会引发错误),但会产生意外的输出。我不明白为什么这不起作用,我认为这与我不明白的细微差别有关。menu()
sample()
%in%
list
choices <- c("rock", "paper", "scissors", "lizard", "spock")
# Scissors [3] beats paper [2],
# paper [2] beats rock [1],
# rock [1] beats lizard [4],
# lizard [4] beats Spock [5],
# Spock [5] beats scissors [3],
# scissors [3] beats lizard [4],
# lizard [4] beats paper [2],
# paper [2] beats Spock [5],
# Spock [5] beats rock [1],
# rock [1] beats scissors [3].
wins <- list(c(3, 2), c(2, 1), c(1, 4), c(4, 5), c(5, 3), c(3, 4), c(4, 2), c(2, 5), c(5, 1), c(1, 3))
fun <- function(){
input <- menu(choices, title="Choose one:")
if (input == 0){
message("You have to pick a valid choice to play this. Try again.")
}
if (input >= 1 && input <= 5){
comp_choice <- sample(1:5, 1)
message(paste0("you chose ", choices[input]))
message(paste0("computer chose ", choices[comp_choice]))
print(list(c(input, comp_choice)) %in% wins)
if (input != comp_choice){
if (list(c(input, comp_choice)) %in% wins) {
message("you won")
}
else message("you lost")
}
else message("it's a draw")
}
}
fun()
意外输出示例(应该是胜利):
Selection: 3
you chose scissors
computer chose lizard
[1] FALSE
you lost
答: 暂无答案
下一个:R:与列表“匹配”中的行为不一致
评论
%in%
print(as.character(list(c(input,comp_choice)))
match
list(as.numeric(c(input, comp_choice))) %in% wins