Search code examples
arrayswords

How to make an array of words? Python


Good afternoon, I wanted to know how to make an array of letters, for example I have a list that is the alphabet:

alphabet=[chr(i) for i in range(ord('a'),ord('z')+1)]

And I want to do with this list a matrix of 5 * 5, which I have done, it has been this, but python gives me error

dimension=5
A= np.zeros((dimension,dimension))
n=0
for j in range(dimension):
    for i in range(dimension):
        A[i][j] = alphabet[n]
        n=n+1 

The error that gives me is this:

Traceback (most recent call last):
  File "Cuestionario 4.py", line 217, in <module>
    A[i][j] = alphabet[n]
ValueError: could not convert string to float: 'a'

Thank you for your attention


Solution

  • replace this

    A= np.zeros((dimension,dimension))
    

    with

    A= np.chararray((dimension, dimension))
    

    Full code should look like this

    dimension=5
    A= np.chararray((dimension,dimension))
    n=0
    for j in range(dimension):
        for i in range(dimension):
            A[i][j] = alphabet[n]
            n=n+1