来自的变量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)