-1

I have two lists, one with a parameter name and one with a pin name, and I am trying to combine the two lists into a 2d matrix but I cannot get the syntax right.

For example:

list1 = [parm1,parm2,parm3]
list2 = [end1,end2,end3]

and I want the matrix to be:

matrix1= [[parm1+ end1,parm1+end2, parm1+end3]
          [parm2+ end1,parm2+end2, parm2+end3]
          [parm3+ end1,parm3+end2, parm3+end3]

right now my code is

for i in range(len(parm_name)):
    for j in range(len(end_name)):
        pin_name[i][j] = parm_name[i] + end_name[j]

and it's not working.

Falko
  • 17,076
  • 13
  • 60
  • 105
sshays68
  • 57
  • 6

2 Answers2

2

Instead of reassigning elements of a preinitialized list, simply create a new one:

list1 = [parm1,parm2,parm3]
list2 = [end1,end2,end3]
matrix1 = [[p+e for e in list2] for p in list1]

That last line can be expanded into the following equivalent code:

matrix1 = []
for p in list1:
    result = []
    for e in list2:
        result.append(p+e)
    matrix1.append(result)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

You can create matrix1 with the following:

matrix1 = [[p_name + e_name for e_name in list2] for p_name in list1]

You don't give much code so it's difficult to say why yours isn't working. I suspect that you don't initialize your matrix appropriately. But you don't need to initialize then assign, you can do it all in one step with list comprehension

sedavidw
  • 11,116
  • 13
  • 61
  • 95