-1

This is continued from this thread: Python matrix, any solution?


Input

from numpy import *
import numpy

x=[['1','7'],
 ['1.5', '8'],
 ['2', '5.5'],
 ['2','9']]

Code

y = x[:, :, None] * x[:, None]
print y.sum(axis=0)

I received error:

"list indices must be integers, not tuple"

But if x is x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]]) then it's ok, but I don't have such input.

Community
  • 1
  • 1
thaking
  • 3,495
  • 8
  • 27
  • 33
  • 2
    Lists are different than numpy arrays. If you want to use numpy operations, you need to convert your lists to arrays first. – recursive Apr 29 '11 at 20:06
  • And how can I do this? I try many thing but with no sucess – thaking Apr 29 '11 at 20:07
  • in the input, you left out the commas after each row. – kefeizhou Apr 29 '11 at 20:10
  • My problem is that I have [['1','7']...] instead [[1,7]...] – thaking Apr 29 '11 at 20:21
  • Please don't `import * from numpy`; that will pollute your namespace with a great bunch of functions and confuse readers of your code (both humans and code analysis tools). If you want to save on typing, prefer `import numpy as np` instead. – Fred Foo Apr 29 '11 at 20:28

2 Answers2

2

Edit:

It's not 100% clear to me what you're asking/trying to achieve here. In response to the comment about having [['1','7'] ...]: Currently you have string elements in your list; you can easily enough convert to numeric elements with:

xf = [[float(el) for el in m] for m in x]

Original post: Define your list by putting commas between your list elements:

x=[['1','7'],['1.5', '8'],['2', '5.5'],['2','9']]

When I didn't do this, I got your error, but by doing this I avoided the error.

GreenMatt
  • 18,244
  • 7
  • 53
  • 79
  • Well I know that, but my input is much larger from that and is random, i cannot add commas between elements! This element's which I have is just example... – thaking Apr 29 '11 at 20:11
  • Why would you not be able to add commas? Perhaps your problem is that you can not add commas, not that you need this to work with no commas. – recursive Apr 29 '11 at 20:16
  • My problem is that I have [['1','7']...] instead [[1,7]...] – thaking Apr 29 '11 at 20:23
1

Convert x to a numpy array of numbers:

x = numpy.asanyarray([[float(z) for z in y] for y in x])
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • This will not solve my problem; My problem is that I have [['1','7']...] instead [[1,7]...] – thaking Apr 29 '11 at 20:21
  • @ant: `map` vs. list comprehensions is a matter of style. I prefer this solution since the comprehension expression mirrors the 2d result matrix. – Fred Foo Apr 30 '11 at 19:42