使用 in 运算符匹配元组中的项目

Using in operator to match items in a tuple

我试图理解为什么下面的 in 运算符不匹配和打印 (4, 'foobar'), and ('foobar', 5) (它匹配其余部分)。试图用元组确定我对 in 的理解。我试图匹配元组任何部分中具有 "foo" 或 "bar" 或 "foobar" 的所有元组。

ls = [(1, 'foo'), ('bar2'), ('foo', 'bar', 3), (4, 'foobar'), ('foobar', 5), ('foobar')]
print [x for x in ls if 'foo' in x or 'bar' in x]
[(1, 'foo'), 'bar2', ('foo', 'bar', 3), 'foobar']

因为 ('bar2') 不是元组,而只是字符串 'bar2' (并且 'bar' 在该字符串中),而 ('foobar', 1)是一个元组并且 'bar' 不是 ('foobar', 1).

之一

'in' 在 list/tuple 和单个字符串上的工作方式不同。当应用于字符串时,它会询问 "is 'foo' a substring?"。当应用于 list/tuple 时,它会询问 "is 'foo' equal to one of the list/tuple items?"。

对于元组,'foo' in x表示"is there an element of x that equals 'foo'",而不是"is there an element of x that contains 'foo'"。

要执行后者,您可以执行类似

的操作
any('foo' in y for y in x)

然而,对于一个字符串,'foo' in x表示"is 'foo' a substring of x"。

此外,括号中的单个元素(例如 ('bar2')('foobar')不会 构成元组。要制作元组,通常需要在括号中加上逗号:('bar2',)('foobar',)。这两个元素都匹配,因为它们不是元组并且包含正确的子字符串。

如果您要专门查找 foobarfoobar,而不是 barfoo 之类的内容,只需在理解中添加一个额外的 or :

[x for x in ls if 'foo' in x or 'bar' in x or 'foobar' in x]

您可以通过执行

之类的操作来概括使用 any
search_terms = ('foo', 'bar', 'foobar')
[x for x in ls if any(a in x for a in search_terms)]