【发布时间】:2021-09-09 00:56:11
【问题描述】:
我正在寻找一种方法来比较 2 个字符串列表。一个列表中有逻辑运算符,例如["abc" or "def" and "ghi"]。如果"abc" 或("def" and "ghi") 在["def", "ghi", "jlk"] 之类的字符串列表中,我正在寻找一些简单的比较。两个列表都来自列表或字典,因此它们都需要是变量。我想做类似以下的事情。
a = ["def", "ghi", "jlk"]
b = ["abc" or "def" and "ghi"]
if b in a:
print("True")
else:
print("False")
我也很难理解为什么我可以在比较中更改一些字符串并仍然得到匹配。以下返回True
a = ["abc", "def", "ghi", "jkl"]
if "abd" and "def" in a:
print("True")
这将返回False。
a = ["abc", "def", "ghi", "jkl"]
if "abc" and "dea" in a:
print("True")
【问题讨论】:
-
这里有一些语法混乱。如果您有
b = ["abc" or "def" and "ghi"],则计算结果为b = ['abc'],因为表达式"abc" or "def" and "ghi"将"abc"计算为真值,并且因为它为真,所以它成为表达式的值。or和and条件是预先评估的,不是列表的一部分。 -
看起来你想使用设置交集并检查它是否非零?
-
其次,如果你评估
if "abd" and "def" in a:,这相当于if "abd" and ("def" in a):,它相当于if "def" in a:,因为"abc"是真的。你可能想要if "abc" in a and "def" in a:。
标签: python logical-operators string-comparison