python - IF 语句不适用于列表差异
问题描述
尝试使用以下代码获取两个列表之间差异的结果,但似乎不起作用。
list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']
list3 = list(set(list1) - set(list2))
if not list3: #if not empty, print list3
print(list3)
else: # if empty print none
print("None")
解决方案
在您的代码示例中,list3
确实是空的,因为其中的所有元素list1
也在其中list2
。
如果您正在寻找一个列表,其中包含 in list1
that not in和 in和 not inlist2
的元素,您应该在这里使用对称集差异,这可以使用operator执行,例如:list2
list1
^
list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']
list3 = list(set(list1) ^ set(list2))
另一方面,如果你正在寻找list2
不在的元素list1
,你应该交换操作数:
list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']
list3 = list(set(list2) - set(list1))
如果您使用-
,您将获得设置差异[wiki](或补码),如下所示:
A ∖ B = { a∈ A | ∉ B }
而对称集差异[wiki](或析取联合)是:
A ⊕ B = (A ∖ B) ∪ (B ∖ A)
注意:注意非空列表的真实性是,空列表的真实性
True
是False
。因此,您可能应该将打印逻辑重写为:if list3: # not empty print(list3) else: # is empty print("None")
推荐阅读
- python - 很想使用 selenium 从 webapge 获取数据并使用烧瓶显示它?
- c# - 如何使用 Linq 使用另一个列表的值对列表进行排序
- angular - 为什么将选项卡添加到 mat-tab-group 不能从单独的组件中工作?
- c++ - 在 C++ 的 fluent interface 中设置后立即调用析构函数
- javascript - 在 Node 的 GET 请求之后将数据传递给 MongoDB
- amazon-web-services - flutter_facebook_login 和 AWS:登录令牌无效。不是有效的 OpenId Connect 身份令牌
- bash - 来自字符串的Bash关联数组?
- python - 无法弄清楚为什么我的 if/else 语句不像我想要的那样工作
- java - Java Parking Ticket Simulator - 类聚合/复制构造函数
- python - 在 MatPlotlib 图中的每个条形顶部添加一条线