本文介绍了Python:从循环中返回值而不会中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我有一个按地点分组的个人列表.我想产生一个新变量,根据每个人的位置给每个人一个数字.我希望数据看起来像这样:

G'day, I have a list of individuals that are grouped by place. I want to produce a new variable that gives a number to each individual dependant on their place. What I would like my data to look like is:

place       individual
here        1
here        2
here        3
there       1
there       2
somewhere   1
somewhere   2

我写了这个:

    nest="ddd", "ddd", "fff", "fff", "fff", "fff", "qqq", "qqq"

    def individual(x):
        i = 0
        j = 1
        while i < len(x):
            if x[i] == x[i-1]:
                print(j+1)
                i = i + 1
                j = j + 1
            else:
                print(1)
                i = i + 1
                j = 1

    individual(nest)

这会打印出我想要的值,但是,当我在其中放回车符时,它会跳出循环并仅返回第一个值.我想知道如何返回这些值,以便将它们作为新列添加到我的数据中?

This prints out the values I want, however, when I put return in there it breaks out of the loop and only returns the first value. I was wondering how I could return these values, so that I can add them to my data as a new column?

我了解到产量吗?但不确定是否合适.谢谢您的帮助!

I read about yield? but was unsure if it is appropriate. Thank you for your help!

干杯,亚当

推荐答案

print(...)替换为yield ....那么您将拥有一个生成器,它将为您提供迭代.然后,可以通过遍历结果将其转换为其他适当的数据结构.例如,要从生成器构建列表,您可以执行以下操作:

replace print(...) with yield .... then you'll have a generator which will give you an iterable. You can then turn that into some other appropriate data-structure by iterating over the result. For example, to construct a list from the generator, you could do:

list(individual(nest))  #this is prefered

在这种情况下,迭代是隐式的...

Where the iteration is implicit in this case ...

或(在这种情况下更全面,但可能提供更多信息):

or (the more round-about but possibly more informative in this context):

[ x for x in individual(nest) ]  #This is just for demonstration.

这篇关于Python:从循环中返回值而不会中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:57