如何从迭代器/生成器中获取第一个元素并将其放回Python中?

时间:2018-12-10 17:10:33

标签: python iterator generator

我想从迭代器中获取第一个元素,对其进行分析,然后放回去并与迭代器一起使用,就好像它未被触摸一样。

现在我写道:

<button [disabled]="thisIsMyForm.get('formArrayName').enabled" (click)="onSubmit()">Submit Form</button>

onSubmit() {
    // Here I would like to be able to access the values of the 'forms'
    console.log(this.thisIsMyForm.value)
  }

可以写得更好/更短吗?

2 个答案:

答案 0 :(得分:0)

请注意,仅当您推回非None值时,此选项才有效。

如果实现生成器功能(即所拥有的功能),以便关心yield 的返回值,则可以在生成器上“推回”(使用{ {1}}):

.send()

在这里,您正在从# Generator def gen(): for val in range(10): while True: val = yield val if val is None: break # Calling code pushed = false f = gen() for x in f: print(x) if x == 5: print(f.send(5)) pushed = True 循环打印x for的返回值(如果调用)。

0
1
2
3
4
5
5   # 5 appears twice because it was pushed back
6
7
8
9

这只能让您往回推一次。如果您想回退更多次,可以执行以下操作:

.send()

产生:

0
1
2
3
4
5  # Pushed back (num_pushed = 0)
5  # Pushed back (num_pushed = 1)
5  # Pushed back (num_pushed = 2)
5  # Not pushed back
6
7
8
9

答案 1 :(得分:0)

以下是一个示例itertools.tee

import itertools
def colors():
    for color in ['red', 'green', 'blue']:
        yield color

rgb = colors()
foo, bar = itertools.tee(rgb, 2)

#analize first element
first =  next(foo)
print('first color is {}'.format(first))

# consume second tee
for color in bar:
    print(color)

输出

first color is red
red
green
blue