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

时间:2019-02-22 13:19:23

标签: python

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

import re
list = ["abc","b","c"]
if any(re.search(r"a",i) for i in list):
    print("yes")
    print(i)

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

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

2 个答案:

答案 0 :(得分:1)

import random random.seed(100) start = [random.randint(0, 10000) for _ in range(300)] end = start = [s + random.randint(0, 3000) for s in start] intervals = list(zip(start, end)) print(np.all(simplify_intervals(intervals) == simplify_intervals_nb(intervals))) # True %timeit simplify_intervals(intervals) # 15.2 ms ± 179 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit simplify_intervals_nb(intervals) # 9.54 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 仅告诉您是否满足条件,但不能让您拥有价值。最Python的方法可能是这样:

any

如果您不喜欢该例外,而是希望使用try: i = next(i for i in list if i == 'a') print(i) except StopIteration: print('No such thing')

if

答案 1 :(得分:1)

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 occurence
for item in with_a:
    print("yes")
    print(item)

输出:

yes
abc
yes
abracadabra