Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用in运算符匹配元组中的项_Python_Tuples_Matching - Fatal编程技术网

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

Python 使用in运算符匹配元组中的项,python,tuples,matching,Python,Tuples,Matching,我试图理解为什么下面的in操作符不匹配并打印(4,'foobar')和('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

我试图理解为什么下面的in操作符不匹配并打印(4,'foobar')和('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]
因为('bar2')不是元组,而是字符串'bar2'(并且'bar'在该字符串中),而('foobar',1)是元组,而'bar'不是('foobar',1)之一


“in”在列表/元组和单个字符串上的工作方式不同。当应用于字符串时,它会询问“foo”是子字符串吗。当应用于列表/元组时,它会询问“foo”是否等于列表/元组项之一?”

对于元组,
中表示“是否有
x
的元素等于
”,而不是“是否有
x
的元素包含

要实现后者,您可以执行以下操作

any('foo' in y for y in x)
search_terms = ('foo', 'bar', 'foobar')
[x for x in ls if any(a in x for a in search_terms)]
但是,对于字符串,x
中的
'foo'表示“是
'foo'
x
的子字符串”

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

如果您专门查找
foo
bar
foobar
,而不是类似于
barfoo
,只需在理解中添加一个额外的

[x for x in ls if 'foo' in x or 'bar' in x or 'foobar' in x]
您可以使用
any
进行如下操作

any('foo' in y for y in x)
search_terms = ('foo', 'bar', 'foobar')
[x for x in ls if any(a in x for a in search_terms)]
('bar2')
不是包含
'bar2'
的元组。它是字符串
'bar2'
的字面意思(不是双关语)。