gpt4 book ai didi

python 值列表,如何?

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:53 25 4
gpt4 key购买 nike

我不知道该怎么说

但我有一个 say 的列表

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

这是排序和索引所以如果我做 l[0] => 'a'

我使用 np.eye(5) 得到对角线 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.]])

但我的目标是得到类似..

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.]])

=============更新===================

np 这里是 numpy 库,不好意思

将 numpy 导入为 np

最佳答案

所以你想用向量创建一个对角线数组,对吧?那是 diag :

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

或者,如果这些是变量而不是字符串:

>>> 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.]])

关于python 值列表,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com