һ 刘
һ 刘

Reputation: 25

assign values executed to array in python

n = 1
for n in range(3):         
    p = Poly(a[n+1][0:3])
    print p 
    n=n+1

this is my coding. basically, I have a 3 times 3 matrix, I want to assign each row to a polynomial function and then assign each polynomial function to a new array. however, i do not know how to assign the value of p each time executed from the poly function to the array I want.

some body please help me.

the output of p executed looks like

basically, it will be good enough to build a 3*1 array from the executed p output.

for imformation , my matrix of a looks like this

[['A', 'B', 'C', 'PMIN', 'PMAX'], ['749.55', '6.95', '9.68*(10^-4)', '320', '800'], ['1285', '7.051', '7.375*(10^-4)', '300', '1200'], ['1531', '6.531', '1.04*(10^-3)', '275', '1100']]
[['A' 'B' 'C' 'PMIN' 'PMAX']

Upvotes: 0

Views: 7897

Answers (3)

Robᵩ
Robᵩ

Reputation: 168626

List comprehensions describe this quite simply:

def Poly(a):
  return "{}x^2 + {}x + {}".format(a[0],a[1],a[2])
a = [['A', 'B', 'C', 'PMIN', 'PMAX'],[1,2,3,99,99],[4,5,6,42,42],[7,8,9,3.14,2.72]]
result = [Poly(a[n]) for n in range(1,4)]
print result

The output is:

['1x^2 + 2x + 3', '4x^2 + 5x + 6', '7x^2 + 8x + 9']

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

however, i do not know how to assign the value of p each time executed from the poly function to the array I want.

results = []
for x in range(3):
   p = Poly(something)
   results.append(p) # adding it to the list `results`

By the way, in Python, there are no arrays, just lists (0-index collections) and dictionaries, which are more like hashes.

Upvotes: 0

askewchan
askewchan

Reputation: 46530

Try this:

p = []
for n in range(3):
    p.append(Poly(a[n+1][0:3]))
print p

I don't have access to your Poly function or a array, but we can test it like this:

p = []
for n in range(3):
    p.append([n,n+1,n+2])
print p
#output:
#[[0, 1, 2],
# [1, 2, 3],
# [2, 3, 4]]

I also removed your lines with n+1 and n=n+1 because both of those are done automatically by using n in range(3) which does the following:

for n in range(3):
    print n
#output:
# 0
# 1
# 2

(note that it starts at 0 and ends with 2, this is so that it runs exactly 3 times)

Upvotes: 0

Related Questions