-1

Need help on this.

I have two list, say, list1 = [2,3,4] and list2 = [5,6,7]. I also have a function that takes two arguments, say, calc(a,b). Now, I want to take arguments form the both of the list. Argument a shall be from list1 and b shall from list 2. The result of the calculation should look something like output of data table in excel (for instance list1 is row variable and list2 is column variable).

What I have done

list1 = [2,3,4]
list2 = [5,6,7]
resultlist = []

def calc(a,b):
    result =  a**2+b
    return result

for i in list1:
    for j in list2:
        c = calc(i,j)
        resultlist.append(c)
print(resultlist)

The output I got [9, 10, 11, 14, 15, 16, 21, 22, 23]

However, I want result to look like

      2     3     4
5     9    14    21
6    10    15    22
7    11    16    23

Thank you!

max
  • 3,915
  • 2
  • 9
  • 25
pat90
  • 1
  • 1
  • Does this answer your question? [How to define a two-dimensional array in Python](https://stackoverflow.com/questions/6667201/how-to-define-a-two-dimensional-array-in-python) – metatoaster Jun 09 '20 at 10:58

1 Answers1

0

Build a list for each row and then append that list to your resultlist:

list1 = [2,3,4]
list2 = [5,6,7]
resultlist = []

def calc(a,b):
    result =  a**2+b
    return result

for i in list1:
    rowlist = []
    for j in list2:
        c = calc(i,j)
        rowlist.append(c)
    resultlist.append(rowlist)
print(resultlist)

Elements are easily accessed:

# First row
print(resultlist[0])
# Last element of first row
print(resultlist[0][-1])

Try it online

You may want to consider pandas if you're after dataframe like behaviour

Erik White
  • 336
  • 2
  • 8
  • Not exactly how I wanted. In continuation to your suggestion, I transposed the list and got what I was looking for. – pat90 Jun 09 '20 at 13:24