junglebambino
junglebambino

Reputation: 46

How can I remove the commas between a list's elements?

Does anyone know how to remove the comma's in this list?

[4.1755139724695871, -2.6367224815727237, 2.3407722739111092, 0.36546242292367692]

It has to be like this:

[ 4.17551397 -2.63672248  2.34077227  0.36546242]

I used this code:

import numpy as np
def ontbinding(A, x):
    N, N = A.shape
    e = np.linalg.eig(A)
    eigenvector = e[1]
    return [np.dot(x.T,(eigenvector[:,i]).T)[0] for i in range(N)]

And the following array and list were given.

A = np.array([[  0.,   0.,   5.,  -2.],
 [  0.,  -4.,   7.,   4.],
 [  5.,   7.,  18.,   3.],
 [ -2.,   4.,   3.,   0.]])
x = np.array([[1.], [2.], [3.], [4.]])

Upvotes: 1

Views: 6835

Answers (3)

itseva
itseva

Reputation: 593

This code must give you the right answer.

 import numpy as np
    def ontbinding(A, x):
        N, N = A.shape
        e = np.linalg.eig(A)
        eigenvector = e[1]
        return np.array([np.dot(x.T,(eigenvector[:,i]).T)[0] for i in range(N)])

Just keep in mind that when you use a comprehension, you will automatically receive a list. When you want to change that list into an array just use:

np.array(list)

Upvotes: 1

hpaulj
hpaulj

Reputation: 231385

You define A and x as arrays; their print representation does not have commas. Your input is in the form of lists, which requires commas.

In [39]: A
Out[39]: 
array([[  0.,   0.,   5.,  -2.],
       [  0.,  -4.,   7.,   4.],
       [  5.,   7.,  18.,   3.],
       [ -2.,   4.,   3.,   0.]])
In [40]: x
Out[40]: 
array([[ 1.],
       [ 2.],
       [ 3.],
       [ 4.]])
In [41]: print(A)
[[  0.   0.   5.  -2.]
 [  0.  -4.   7.   4.]
 [  5.   7.  18.   3.]
 [ -2.   4.   3.   0.]]
In [42]: print(x)
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]]

Your function returns a list, the result of list comprehension, [... for i in range(N)].

In [44]: y = ontbinding(A,x)
In [45]: y
Out[45]: 
[4.1755139724695871,
 -2.6367224815727233,
 2.3407722739111088,
 0.36546242292367614]

You could turn that into an array:

In [46]: np.array(y)
Out[46]: array([ 4.17551397, -2.63672248,  2.34077227,  0.36546242])
In [47]: print(np.array(y))
[ 4.17551397 -2.63672248  2.34077227  0.36546242]

Upvotes: 2

Prune
Prune

Reputation: 77837

The list, per se, has no commas. That's only the print image (generated with str or __repr__) that inserts the commas as the default output rendering. What you can do with such an object is to make the image explicitly, remove the commas, and print that.

list_str = str(list).replace(',', '')
print list_str

Is that what you need?

Upvotes: 4

Related Questions