简体   繁体   English

如何在Lambda,Python中保存索引

[英]How to save an index in lambda, python

I'm trying to do the following: 我正在尝试执行以下操作:

>>>func = lambda string,i=0: string[index]

>>> func('HEY')
H
>>> func('HEY')
E
>>> func('HEY')
Y

How can i save and increment index each time(without creating index as global) thanks 我如何每次都可以保存和增加索引(不将索引创建为全局索引),谢谢

Solution 1 解决方案1

You can create a generator function, like this 您可以像这样创建一个生成器函数

def get_next_char(actual_string):
    for char in actual_string:
        yield char

Then, you need to create a generator object, like this 然后,您需要创建一个生成器对象,像这样

next_char = get_next_char("HEY")

That's it. 而已。 You can now get the next character with next function, like this 您现在可以使用next函数获取下一个字符,如下所示

>>> next(next_char)
H
>>> next(next_char)
E
>>> next(next_char)
Y

Solution 2 解决方案2

You can simply use the String's iterator, like this 您可以像这样简单地使用String的迭代器

get_char = iter("HEY")
>>> next(get_char)
H
>>> next(get_char)
E
>>> next(get_char)
Y

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

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