Python: returns values ​​from a loop without breaking

G'day, I have a list of people who are grouped by location. I want to create a new variable that gives a number to each person depending on their place. I would like my data to look like this:

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

I wrote this:

  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 return there, it breaks out of the loop and returns only the first value. I was wondering how can I return these values ​​to add them to my data as a new column?

Did I read about the crop? but was not sure how appropriate it was. Thanks for the help!

Cheers, Adam

+4
source share
1 answer

replace print(...) with yield ... then you will have a generator that will give you iterability. You can then turn this into some other appropriate data structure by repeating the result. For example, to build a list from a generator, you can do:

 list(individual(nest)) #this is prefered 

If the iteration is implicit in this case ...

or (more round, but perhaps more informative in this context):

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

Source: https://habr.com/ru/post/1442841/


All Articles