Python:一行循环条件

4
在下面的例子中,我正在测试变量“characters”中是否有任何字符在字符串“hello”中被找到。
characters = ['a','b','c','d']

if True in [c in 'hello' for c in characters]: print('true')
else: print('false')

一行循环创建了一个布尔值列表。我想知道是否有任何方法可以不创建列表,而是在循环中的任一条件通过后立即传递整个条件。
4个回答

6
你可以使用生成器表达式与any一起使用。这将逐个从生成器中取出值,直到生成器耗尽或其中一个值为真。
与列表推导式不同,生成器表达式只会在需要时计算值,而不是一次性计算所有值。
if any(c in 'hello' for c in characters):
    ...

4
是的,您可以使用内置函数any来实现这个功能。
if any(c in 'hello' for c in characters): print('true')

0
你可以使用set的交集来获取两个文本的重复字符。如果有任何字符在其中,它们就在交集中。如果交集为空,则没有字符在其中:
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 + hello true # abcd + apple


0

尝试在之前声明列表。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接