Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表中使用运算符_Python - Fatal编程技术网

Python 在列表中使用运算符

Python 在列表中使用运算符,python,Python,我想检查字符串是否在列表中,也要检查它是否不在列表中: 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 =

我想检查字符串是否在列表中,也要检查它是否不在列表中:

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']
然后,它不运行该操作,并说a not in supplies为False,这是不正确的

如何将not输入列表b,使其作为操作员运行


谢谢

我想这可能会实现您想要实现的目标:

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))

如果我理解正确的话,您正在尝试计算
m
中的每个值是否在
供应中。试试这个:

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)

例如,您可以使用eval()函数:

print(m[x], b[j], eval("'%s' %s in supplies" % (m[x], b[j])))
变量b应该类似于:

b = ['','not']

不能在列表中存储运算符。同样,请尝试
foo=[+,-,/,*]
。它不工作——操作员必须操作

您可以做的是创建一个执行该操作的函数,并存储它

b = [("in", lambda el, lst: el in lst),
     ("not in", lambda el, lst: el not in lst)]

for word in m:  # why are you indexing this?
    for desc, f in b:  # or this?
        if f(word, supplies):
            print(word, desc, "list 'supplies'")

不确定您到底在寻找什么,但它是不是不在耗材中的字符串?您可能想在耗材中使用xnor
b[j]
m[x]吗?我不相信您可以将操作员存储在列表中。你到底想干什么?为什么不能只说
如果物品在供应品中
如果物品不在供应品中
?请注意,eval是危险的,特别是如果用户对
供应品中的物品有任何控制权