gpt4 book ai didi

python - 如何检查一个变量是否存在于多个列表中?

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:45 25 4
gpt4 key购买 nike

这是我的代码的摘录!

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”。如何检查一个变量是否存在于多个列表中?我试图在列表中创建列表,但我仍然得到“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 谢谢!!!

最佳答案

测试选择是否在列表的任何中:

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 for 的结果[除法、乘法、减法、加法] 中任何可能的 ls

如果这些列表中的一个包含选择any 将返回 True,否则返回 False。

关于python - 如何检查一个变量是否存在于多个列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com