Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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:循环条件的一行_Python_Python 3.x_Loops_Syntax - Fatal编程技术网

Python:循环条件的一行

Python:循环条件的一行,python,python-3.x,loops,syntax,Python,Python 3.x,Loops,Syntax,在下面的示例中,我正在测试是否在字符串“hello”中找到变量“characters”中的任何字符 characters = ['a','b','c','d'] if True in [c in 'hello' for c in characters]: print('true') else: print('false') 循环的一行创建一个布尔值列表。我想知道是否有任何方法不创建列表,而是在循环中的一个条件通过后传递整个条件。可以与生成器表达式一起使用。这将从生成器中一次获取一个值,直到生

在下面的示例中,我正在测试是否在字符串“hello”中找到变量“characters”中的任何字符

characters = ['a','b','c','d']

if True in [c in 'hello' for c in characters]: print('true')
else: print('false')
循环的一行创建一个布尔值列表。我想知道是否有任何方法不创建列表,而是在循环中的一个条件通过后传递整个条件。

可以与生成器表达式一起使用。这将从生成器中一次获取一个值,直到生成器耗尽或其中一个值为真

生成器表达式将仅根据需要计算值,而不是像列表那样一次计算所有值

if any(c in 'hello' for c in characters):
    ...

是的,您可以使用内置功能
any

if any(c in 'hello' for c in characters): print('true')

您可以使用
设置
的交叉点来获取两个文本的交叉字符。如果有,则它们在其中;如果intersect-
集合
为空,则不在其中:

characters = set("abcd")  # create a set of the chars you look for
text = "hello"
charInText = characters & set(text) # any element in both sets? (intersection)
print ( 'true' if charInText != set() else 'false')  # intersection empty?

text = "apple"
charInText = characters & set(text) 
print ( 'true' if charInText != set() else 'false') 
输出:

false#abcd+你好
正确#abcd+apple

请在前面声明列表,尝试此操作

characters = ['a','b','c','d']
    a = []
    if True in a = [c in 'hello' for c in characters]: print('true')
    else: print('false')