繁体   English   中英

Python:循环条件的一行

[英]Python: One line for loop condition

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

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

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

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

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

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

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

是的,你可以使用内置的功能, any为。

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

您可以使用set的交集来获取两个文本的交叉字符。 如果你有任何东西,它们就在其中,如果交叉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

通过以前声明列表来尝试这个。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM