简体   繁体   English

python在函数中使用yield

[英]python using yield from in a function

i have a list like: 我有一个列表,如:

list=['2,130.00','2,140.00','2,150.00','2,160.00']

i would like to use a function like 我想使用像这样的功能

def f(iterable):
    yield from iterable

and applying 并申请

float(item.replace(',','')) for item in iterable

at the same time so that 同时这样

f(list)

returns 回报

[2130.00,2140.00,2150.00,2160.00]

I know 我知道

[float(x.replace(',','')) for x in list]

works here but it is to understand how to use yield from in a function and modifying items in the iterable at the same time. 在这里工作,但它是要了解如何在函数中使用yield和同时修改iterable中的项目。 Maybe i have to use *args and/or **kwargs in the function but not sure i have and how to. 也许我必须在函数中使用* args和/或** kwargs但不确定我有和如何。

yield from is a pass-through; yield from是一种传递; you are delegating to the iterable. 你委托给iterable。 Either wrap the iterable in a generator expression to transform elements, or don't use yield from but an explicit loop: 将iterable包装在生成器表达式中以转换元素,或者不使用yield from而是使用显式循环:

def f(iterable):
    yield from (i.replace(',', '') for i in iterable)

or 要么

def f(iterable):
    for item in iterable:
        yield item.replace(',', '')

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

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