Domanda

i'm not sure how can I word this

but I have a list of say

l = ['a','b','c','d','e']  

this is sorted and index so if I do l[0] => 'a'

i use np.eye(5) to get diagonal 1

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

but my goal is to get something like ..

array([[ a., 0., 0., 0., 0.], 
[ 0., b., 0., 0., 0.], 
[ 0., 0., c., 0., 0.], 
[ 0., 0., 0., d., 0.], 
[ 0., 0., 0., 0., e.]])

=============update===================

np here is numpy library, sorry

import numpy as np

È stato utile?

Soluzione 2

Depending on the answer for @abarnert question you may think about using SymPy:

>>> from sympy import Symbol
>>> np.diag([Symbol(x) for x in ['a','b','c','d','e']])
array([[a, 0, 0, 0, 0],
       [0, b, 0, 0, 0],
       [0, 0, c, 0, 0],
       [0, 0, 0, d, 0],
       [0, 0, 0, 0, e]], dtype=object)

Altri suggerimenti

So you want to create a diagonal array out of a vector, right? That's diag:

>>> l = ['a','b','c','d','e']  
>>> np.diag(l)
array([['a', '', '', '', ''],
       ['', 'b', '', '', ''],
       ['', '', 'c', '', ''],
       ['', '', '', 'd', ''],
       ['', '', '', '', 'e']],
      dtype='|S1')

Or, if those are meant to be variables rather than strings:

>>> a, b, c, d, e = 1., 2., 3., 4., 5.
>>> l = [a, b, c, d, e]
>>> np.diag(l)
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.,  0.],
       [ 0.,  0.,  3.,  0.,  0.],
       [ 0.,  0.,  0.,  4.,  0.],
       [ 0.,  0.,  0.,  0.,  5.]])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top