Python:如何从 any() 可迭代对象中引用对象

我正在尝试引用我正在匹配的对象。


import re

list = ["abc","b","c"]

if any(re.search(r"a",i) for i in list):

    print("yes")

    print(i)

这有效,只是不是最后一个print命令。


有什么办法可以做我在这里尝试做的事情吗?


慕婉清6462132
浏览 172回答 2
2回答

蛊毒传说

来自的变量any()不会超出它的范围——它们只在它内部知道。您只是匹配简单的字母 - 您可以使用列表理解从列表中获取包含此字母的所有项目:my_list = ["abc","b","c","abracadabra"]with_a  = [ item for item in my_list if "a" in item] # or re.find ... but not needed here# this prints all of them - you can change it to if ...: and print(with_a[0])# to get only the first occurencefor item in with_a:    print("yes")    print(item)输出:yesabcyesabracadabra

扬帆大鱼

any只告诉你是否有任何东西满足条件,它不会让你拥有价值。最pythonic的方法可能是这样的:try:    i = next(i for i in list if i == 'a')    print(i)except StopIteration:    print('No such thing')如果您不喜欢异常并且宁愿使用if:i = next((i for i in list if i == 'a'), None)if i:    print(i)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python