我有这样的名单:
Action=[A,B,C,D,E,F,G,H,I]
a=[A,B,E,I]
b=[C,D,F,G,H]
所以,我想得到对应于a和b的动作向量,这就像这样
Action=[a,a,b,b,a,b,b,b,a]
如何在R或python中完成?
答案 0 :(得分:1)
我假设这些值是字符。
您可以在R
中执行以下操作A <- c('A','B','C','D','E','F','G','H','I')
a <- c('A','B','E','I')
b <- c('C','D','F','G','H')
Action <- character(length(A))
Action[which(A %in% a)] <- 'a'
Action[which(A %in% b)] <- 'b'
Action
# [1] "a" "a" "b" "b" "a" "b" "b" "b" "a"
你可以在Python中使用列表理解
A = ['A','B','C','D','E','F','G','H','I']
a = ['A','B','E','I']
b = ['C','D','F','G','H']
Action = ['a' if i in a else 'b' if i in b else None for i in Action]
print(Action)
# ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'b', 'a']
答案 1 :(得分:0)
在R中,像这样使用ifelse
:
ifelse(A %in% a, "a", "b")
## [1] "a" "a" "b" "b" "a" "b" "b" "b" "a"
答案 2 :(得分:0)
在python中,您可以使用字典:
Action = ['A','B','C','D','E','F','G','H','I']
a = ['A','B','E','I']
b = ['C','D','F','G','H']
d = {}
for elem in a:
d[elem] = 'a'
for elem in b:
d[elem] = 'b'
result = [d[action] for action in Action if action in d]
print(result)
哪个输出:
['a', 'a', 'b', 'b', 'a', 'b', 'b', 'b', 'a']