如何使用生成器遍历元素并在 python 中进行转换

how to loop through elements using generator and make transformation in python

我试图更好地了解如何在 python

中使用 generator

假设我有以下功能:

names = ["john \t", " dave", "ana", " jenny"]


def function_for_generator(names):

    transformed_names = []

    for name in names:
        if name.endswith("\t"):
            cleaned_name = name.rstrip("\t").replace(" ", "")
            transformed_names.append(cleaned_name)
        elif name.startswith(" "):
            cleaned_name = name.lstrip()
            transformed_names.append(cleaned_name)
        else:
            transformed_names.append(name)
    return transformed_names
  

调用此函数后的当前结果:['john', 'dave', 'ana', 'jenny']

我能够使用 while loopiterator 重写一些接近于此的内容,但我正在寻找的解决方案是专门使用 generator 重写此函数?

如果有人可以帮助我使用 generatorfor loopwhile loop 重写该函数,就我自己的理解而言,谢谢。

这是您期望的生成器函数的代码:

names = ["john \t", " dave", "ana", " jenny"]

def function_for_generator(names):
    for name in names:
        if name.endswith("\t"):
            cleaned_name = name.rstrip("\t").replace(" ", "")
            yield cleaned_name
        elif name.startswith(" "):
            cleaned_name = name.lstrip()
            yield cleaned_name
        else:
            yield name

您可以迭代此生成器函数,如下所示:

for x in function_for_generator(names):
    print(x)

或者像这样:

transformed_names = [x for x in function_for_generator(names)]

鉴于您问题中的具体值,则:

names = ["john \t", " dave", "ana", " Jenny"]

def function_for_generator(names):
  for name in names:
    yield name.strip()

for name in function_for_generator(names):
  print(name)

或者,如果您只想要一个新列表,那么:

newlist = list(function_for_generator(names))

之所以有效,是因为 strip() 删除了前导和尾随空格