简体   繁体   中英

python using arrays to make a matrix

I am trying to make a matrix out of arrays

Suppose My inputs are two arrays

       my_column = [['a','2'] ['k','34','2'] ['d','e','5']]
       my_row = ['a' '2' 'k' '34' 'd' 'e' '5']

I want an output like this

             #a    #2     #k     #34    #d    #e    #5
      #a,2    1     1     0       0      0     0     0
     #k,34,2  0     1     1       1      0     0     0
     #d,e,5   0     0     0       0      1     1     1

However, I am representing this output in a 2D list. My desired output is this

      output_matrix = [['1', '1', '0', '0', '0', '0', '0'],['0', '1', '1', '1', '0', '0', '0'],['0', '0', '0', '0', '1', '1', '1']] 

I am matching my row and column and getting a matrix of 1s if matched and 0 otherwise. #stuff is just a comment for better understanding.

       output_matrix = [[]]
       for i in output_matrix:
          for j in i:
              if my_row[i] == my_column[i][j]:
                 output_matrix.append(1)
              else:
                  output_matrix.append(0)

I am trying to create a new 2D list and store values in that.However, my entire approach seems to be wrong as I get the output as just [ [ ] ]

This uses numpy...

import numpy as np
my_column = [['a','2'], ['k','34','2'], ['d','e','5']]
my_row = ['a', '2', 'k', '34', 'd', 'e', '5']

results = np.zeros((len(my_column), len(my_row)))

for i in range(0, len(my_column) ):
    for j in my_column[i]:
        for ind, x in enumerate(my_row):
            if x == j: 
                results[i,ind] = 1

results

array([[ 1.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  1.,  1.]])

Given the input you provide (i had to add commas between the items in the lists), and the output you want, this does the trick:

my_column = [['a','2'], ['k','34','2'], ['d','e','5']]
my_row = ['a', '2', 'k', '34', 'd', 'e', '5']

output_matrix = []
for r in my_column:
    print "r=",r
    output_matrix.append([])
    for c in my_row:
        print "c=",c
        if c in r:
            output_matrix[-1].append(1)
        else:
            output_matrix[-1].append(0)
print output_matrix

Output is:

[[1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1]]

BTW I would say your names my_column and my_row are the wrong way round - ie the column should be the inner lists, the row should be the outer lists.

Another way of doing this would be to first create an array (a list of lists) of the requisite size with all values 0, then go in and write the 1s where there are matches.

# construct a matrix with as many columns as my_row and as many rows as my_column
output_matrix1 = [[0 for c in my_row] for r in my_column]
for x,colvalue in enumerate( my_row ):
    for y, rowvalue in enumerate( my_column ):
        if colvalue in rowvalue:
            output_matrix1[y][x] = 1
print output_matrix1
my_column = [['a','2'],['k','34','2'],['d','e','5']]
my_row = ['a', '2', 'k', '34', 'd', 'e', '5']

output = []
for elem in my_column:
    output_row = []
    for val in my_row:
        if val in elem:
            output_row.append(1)
        else:
            output_row.append(0)
    output.append(output_row)
print output

This will print out:

[[1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1]]

Your default output is definitely correct. If you want specific output, you can code your own like:

# Cosmetic variables
padding = 8
truncating = 6

# Data prepared for printing.
my_column = [truncating*'-'] + ['a', '2', 'k', '34', 'd', 'e', '5']
my_row = [['a', '2'],[ 'k', '34', '2'],['d', 'e', '5']]
output_matrix = [['1', '1', '0', '0', '0', '0', '0'],['0', '1', '1', '1', '0', '0', '0'],['0', '0', '0', '0', '1', '1', '1']]


for element in my_column:
    print('#{:{}.{}}'.format(''.join(element), padding, truncating), end="")
else:
    print()

for index, list in enumerate(output_matrix):
    print('#{:{}.{}}'.format(','.join(my_row[index]), padding, truncating), end="")

    for element in list:
        print(' {:{}.{}}'.format(''.join(element), padding, truncating), end="")
    else:
        print()

Python 3.x

The result is close to your wish:

#------  #a       #2       #k       #34      #d       #e       #5 
#a,2      1        1        0        0        0        0        0
#k,34,2   0        1        1        1        0        0        0
#d,e,5    0        0        0        0        1        1        1

How can you do this by-self?

Website: Using % & .format()

Documentation: Format String Syntax

Cheer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM