以下是我的代码的摘录!
division = ["Division","Divide","/","div"]
multiplication =["*","x","times","multiply","multiplication","multiple"]
subtraction = ["-",'minus','subtract','subtraction']
addition = ['+','plus','addition','add']
root = ['root','squareroot','square root']
square = ['square','squared','power 2']
choice = input('calculation type')
print(choice == (division or multiplication or subtraction or addition))
到目前为止,它只给出“假”。 如何检查多个列表中是否存在变量? 我试图在列表中创建列表,但我仍然得到“False”,这是代码......
division = ["Division","Divide","/","div"]
multiplication = ["*","x","times","multiply","multiplication","multiple"]
subtraction = ["-",'minus','subtract','subtraction']
addition = ['+','plus','addition','add']
root = ['root','squareroot','square root']
square = ['square','squared','power 2']
basic_double = [division,multiplication,subtraction,addition]
basic_single = [root,square]
choice = input('calculation type')
print(choice == basic_double or basic_single)
任何帮助将不胜感激! :D谢谢!!!
答案 0 :(得分:2)
测试choice
是否在列表的any
中:
any(choice in ls for ls in [division, multiplication, subtraction, addition])
如果给定迭代的至少一个元素是真实的,则 any
返回True。
choice in ls
测试choice是否是列表的元素。
choice in ls for ls in [division, multiplication, subtraction, addition]
是一个生成器理解,这意味着它是一个迭代器,它为choice in ls
中任何可能的ls
返回[division, multiplication, subtraction, addition]
的结果。
如果这些列表中的一个包含choice
,则any
将返回True,否则返回False。
答案 1 :(得分:2)
您可以使用itertools.chain()
检查所有列表中的选项:
if choice in chain(division, multiplication, subtraction, addition):
答案 2 :(得分:0)
现在,您将String,choice与一系列列表进行比较。当您比较两种不同的数据类型时,这将永远不会是真的。
您应该使用“in”关键字检查每个列表
if choice in division:
#this returns true if the String set to choice is in the list of objects in division.
else if choice in multiplication:
.
.
.
此比较将帮助您在列表中找到您要查找的单词。
答案 3 :(得分:0)
如果您想检查Choise是否在您的示例中提供的四个列表中的任何一个:
if choice in division + multiplication + subtraction + addition:
# do something when its in any of it.
...
答案 4 :(得分:0)
现在,您的代码在print函数中进行了以下比较:
choice == ["Division","Divide","/","div"] or ["*","x","times","multiply","multiplication","multiple"] or ["-",'minus','subtract','subtraction'] or ['+','plus','addition','add']
由于short-circuiting,这会减少为:
choice == ["Division","Divide","/","div"]
始终评估为False
,因为choice
不是列表。
我将包含[division, multiplication, subtraction, addition]
的列表展平,然后测试以查看该列表中是否有choice
。
flattened = [item for ls in [division, multiplication, subtraction, addition] for item in ls]
print(choice in flattened)