python - Python - 'And' 运算符在 if 函数中无法正常使用字典
问题描述
在 Python 中使用字典时, and
and运算符似乎有问题。in
我有一本字典,里面列出了不同的衣服,我有一个单独的函数可以从字典中删除这些项目。
clothes = {"socks": 1, "shoes": 2}
def status():
if "socks" and "shoes" in clothes:
print("You are wearing socks and shoes.")
elif "socks" in clothes:
print("You are wearing only socks.")
elif "shoes" in clothes:
print("You are wearing only shoes.")
else:
print("You are not wearing socks or shoes.")
如果我在衣服字典中有两个socks
orshoes
变量,它将打印You are wearing socks and shoes.
. 但是,如果我删除任何一个,它仍然可以实现第一个if
功能,就好像两者都为真一样,但事实并非如此。只有当我删除两者时,我才会得到不同的输出,然后跳转到else
函数。
我假设这是in
操作员的问题,或者我没有正确理解and
操作员的工作,但是从阅读文档来看Returns True if both statements are true
,我有点不知所措。
我敢肯定还有其他方法可以解决这个问题,但我不太确定为什么它在这里不起作用。有什么线索吗?
解决方案
在第一行中,您忘记检查“袜子”是否在衣服中。
if "socks" in clothes and "shoes" in clothes:
print("You are wearing socks and shoes.")
推荐阅读
- regex - sed 用部分匹配替换字符串
- apache-spark - 从 DataFrame 中提取字符串
- r - R中跨多个UTM区域的投影
- asp.net-mvc - 通过来自 IdentityServer 4 的 OpenId 进行 MVC 角色授权
- javascript - 测试函数中的while循环在Jest中只执行一次
- python-3.x - 如何从 BeautifulSoup 对象分解和平滑标签?
- c - 抛出异常:读取访问冲突。pn 为 0x2。在 C 中使用 GTK 时
- javascript - TypeScript - 根据另一个函数的返回类型推断函数的参数类型
- security - 创建 VMware 来宾的原始磁盘映像的最简单方法是什么?
- flutter - 嵌套的 if 和 else 语句在 Flutter 或 dart 中如何工作?