0

I am using below code and it works fine.

def indicators(a,b):
netsum  = []
for a1 in a:
    for b1 in b:
        
        netsum.append(a1 + b1)
        
return netsum

a = [1,2]
b = [3,5]

[print(i) for i in indicators(a,b)]

And, it just prints results as below:

4
6
5
7

What I would like to have is something like below:

a=1,b=3,4
a=1,b=5,6
a=2,b=3,5
a=2,b=5,7

How can I do this? Simply, I want to print indicators value besides result.

Cem
  • 9
  • 1
    Besides the question asked, the indentation should be fixed first. – Daniel Hao Oct 01 '22 at 15:22
  • For the last line, [use list comprehensions for just side effects is very anti-Pythonic](https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects). – Mechanic Pig Oct 01 '22 at 16:01

3 Answers3

1

There are lots of ways to do this. Here's one

def indicators(a,b):
    for a1 in a:
        for b1 in b:
            yield (f"a={a1}, b= {b1}, {a1+b1}")

a = [1,2]
b = [3,5]

for i in indicators(a,b):
    print(i)
user19077881
  • 3,643
  • 2
  • 3
  • 14
  • It's a good one - last yield can be simplified to ```yield (f"{a1=}, {b1=}, {a1+b1}")``` and get same outputs. – Daniel Hao Oct 01 '22 at 15:34
0

Here is your code, glad to help:

def indicators(a, b):
    netsum = []
    for a1 in a:
        for b1 in b:
            sum_value = a1 + b1
            str_result = "a=" + str(a1) + ", b=" + str(b1) + "," + str(sum_value)
            netsum.append(str_result)
    return netsum

a = [1, 2]
b = [3, 5]

[print(i) for i in indicators(a, b)]

Result:
enter image description here

BouRHooD
  • 200
  • 1
  • 14
-1

If you want to print it outside your function, I think the best way is to return every data you need from your indicators function.

I like to use namedtuple for this, I find it more readable. One solution would be:

from collections import namedtuple

Indicated = namedtuple('Indicated', ['a', 'b', 'sum'])


def indicators(a, b):
    netsum = []
    for a1 in a:
        for b1 in b:

            netsum.append(Indicated(a1, b1, a1 + b1))

    return netsum


a = [1, 2]
b = [3, 5]

print("\n".join(
    f"a={i.a}, b={i.b}, {i.sum}"
    for i in indicators(a, b)
))

The idea of this namedtuple is that you join the result of your operation with related details encapsulated in a single data structure.

Nicolas Appriou
  • 2,208
  • 19
  • 32