-4

I have this method:

def filter_verdi_total_fruit_cost(file_name):
    output = []
    for token in file_name.split('\n'):
        items = token.split()
        if len(items) > 2 and items[1] in fruit_words:
            output.append((items[1], items[-1]))
            for _, v in output:
                return v

print(filter_verdi_total_fruit_cost(verdi50))

And it prints just one value: 123,20.

But when I replace return v with: print(v) it prints all the values, when I am calling the method: print(filter_verdi_total_fruit_cost(verdi50))

123,20
2.772,00
46,20
577,50
69,30
3.488,16
137,50
500,00
1.000,00
2.000,00
1.000,00
381,2

But this I don't understand. I just return v. and then it prints just one value. If I do a print(v) it prints all the values.

Question: How can I return all the values in the method, without the print statement?

mightycode Newton
  • 3,229
  • 3
  • 28
  • 54
  • 3
    `return` causes the function to immediately exit. So your function stops after just one loop iteration. – John Gordon Oct 29 '22 at 16:44
  • You missed part of the description of your program: Your sample output should include `None` as the last line. – quamrana Oct 29 '22 at 16:46
  • 1
    Another simple fix could be to replace return with yield, then: for i in filter_verdi_total_fruit_cost(file_name): print(i) but admittedly that's not the easiest to understand/manipulate. – Swifty Oct 29 '22 at 16:53

2 Answers2

2

When you invoke the returnstatement, your function is stopped and returns a value.

You can print the elements outside the function like this, returning the array with all the tuples.

def filter_verdi_total_fruit_cost(file_name):
    output = []
    for token in file_name.split('\n'):
        items = token.split()
        if len(items) > 2 and items[1] in fruit_words:
            output.append((items[1], items[-1]))
    return [v for _, v in output]

print(x for x in filter_verdi_total_fruit_cost(verdi50))
Rodrigo Guzman
  • 487
  • 2
  • 9
1

To return all the values in output as a list, change this:

            for _, v in output:
                return v

to this:

    return [v for _, v in output]

Note that it needs to be outside of the for loop (i.e. de-indented to the same level as output = []) so that it won't happen until you've finished building the entire output list.

You could also write this as a list comprehension rather than appending to a list, e.g.:

def filter_verdi_total_fruit_cost(file_contents):
    return [
        items[-1] for items in (
            token.split() for token in file_contents.split('\n')
        ) if len(items) > 2 and items[1] in fruit_words
    ]
Samwise
  • 68,105
  • 3
  • 30
  • 44