2014-04-27 68 views
0

我有两个列表:的Python做数学与列表,列表转换到矩阵

list_1 = sorted(random.sample(xrange(1, 101), 10)) 
print list_1 

list_2 = sorted(random.sample(xrange(1, 101), 10)) 
print list_2 

注:在我的实际项目,列表中的一个从用户输入构建。

然后我想将它们转换为矩阵并做一些简单的数学运算。例如,也许将一个矩阵从1x10反转为10x1,这样我可以将它们相乘,或者类似的东西。

我该怎么做?我已经阅读过有关NumPy和SciPy等软件包,但我对Python非常陌生,不知道如何安装这些软件包,或者甚至需要他们提供的功能。我会很感激任何建议。

+1

如果你只是处理数字,然后NumPy的可能是你想要的东西。它包含在大多数标准的python发行版中。它的文档是[here](http://wiki.scipy.org/Tentative_NumPy_Tutorial)。 – aruisdante

+0

@aruisdante谢谢。当我尝试'从numpy导入*'我得到'ImportError:没有名为numpy的模块。我正在运行从python.org下载的Python 2.7.6。难道我做错了什么? – pez

+1

NumPy是一个单独的库。您可以从[Python NumPy包页面](https://pypi.python.org/pypi/numpy)下载库。 – sfletche

回答

1

这里是inner productsouter products一个基本的例子:

import random 
import numpy 

list_1 = sorted(random.sample(xrange(1, 101), 10)) 
list_2 = sorted(random.sample(xrange(1, 101), 10)) 

A = numpy.array(list_1).reshape(1,10) 
B = numpy.array(list_2).reshape(10,1) 

# Inner product 
print A.dot(B) 

# Outer product 
print A.T.dot(B.T) 

与像输出:

[[22846]] 
[[ 5 21 26 33 41 42 43 74 78 81] 
[ 15 63 78 99 123 126 129 222 234 243] 
[ 105 441 546 693 861 882 903 1554 1638 1701] 
[ 110 462 572 726 902 924 946 1628 1716 1782] 
[ 135 567 702 891 1107 1134 1161 1998 2106 2187] 
[ 165 693 858 1089 1353 1386 1419 2442 2574 2673] 
[ 190 798 988 1254 1558 1596 1634 2812 2964 3078] 
[ 270 1134 1404 1782 2214 2268 2322 3996 4212 4374] 
[ 375 1575 1950 2475 3075 3150 3225 5550 5850 6075] 
[ 465 1953 2418 3069 3813 3906 3999 6882 7254 7533]] 

注意,我使用.dot为矩阵乘法。如果你没有你的成对操作:

# Matrix multiply 
C = numpy.array([[1,2],[3,4]]) 
print C.dot(C) 

# Pairwise operation 
print C*C 

与结果:

[[ 7 10] 
[15 22]] 
[[ 1 4] 
[ 9 16]]