我想检查字符串是否在列表中并检查它是否也不在列表中:
supplies = ['pens','staplers','flame-throwers','binders']
m = ['pens','a']
b = ['',not]
for x in range(len(m)):
for j in range(len(b)):
print(m[x] , b[j] , m[x] + b[j] in supplies)
但是我遇到语法错误:
b = ['',not]
如果我将其更改为:
b = ['','not']
然后它没有运行该操作并且说没有供应品是假的,这是不正确的。
如何不输入列表b以便它作为运算符运行?
由于
答案 0 :(得分:1)
如果我理解正确,您正试图找出m
中的每个值是否在supplies
中。试试这个:
supplies = ['pens','staplers','flame-throwers','binders']
m = ['pens','a']
# this will iterate each item in the list m, no need to iterate over m indices in this case
for item in m:
print(item, item in supplies)
答案 1 :(得分:0)
我认为这可能会做你想要实现的目标:
supplies = ['pens','staplers','flame-throwers','binders']
m = ['pens','a']
b = [True,False] #True if we want to see if the element is in the list,
#False if we want to see if it is not in the list
for x in range(len(m)):
for j in range(len(b)):
print(m[x] , b[j] , b[j] == (m[x] in supplies))
或者,如果你无法控制b的格式,那就是一个稍微复杂的解决方案:
supplies = ['pens','staplers','flame-throwers','binders']
m = ['pens','a']
b = ['','not']
for x in range(len(m)):
for j in range(len(b)):
print(m[x] , b[j] , (b[j]== 'not') != (m[x] in supplies))
答案 2 :(得分:0)
您无法在列表中存储运算符。同样尝试#add an appropriately named package to the search() path
attach(environment(), name = "package:pkg")
#source the functions
sys.source("test.R", envir = as.environment("package:pkg"))
。它不起作用 - 操作员必须操作!
你 做的是创建一个执行该操作的函数,并将其存储起来。
src
答案 3 :(得分:-1)
例如,您可以使用eval()函数:
print(m[x], b[j], eval("'%s' %s in supplies" % (m[x], b[j])))
变量b应该是:
b = ['','not']