0

I am running the following script, but it is not giving me the desired output. It's printing the last element only; i want to print each element.

a = ([0.1, 0.2, 0.43, 0.44,0.55,0.36,0.57,0.58,0.39,0.40])
for k in range(len(a)):
   # print(a[i])
   #print (a[k])
    import numpy as np

array = np.array([[i, j,a[k]] 
                  for i in range(1, 5)
                  for j in range(i + 1, 6)])
array

Expected output

array([[ 1,  2, 0.1],
       [ 1,  3, 0.2],
       [ 1,  4, 0.43],
       [ 1,  5, 0.44],
       [ 2,  3, 0.55],
       [ 2,  4, 0.36],
       [ 2,  5, 0.57],
       [ 3,  4, 0.58],
       [ 3,  5, 0.39],
       [ 4,  5, 0.40]])
3
  • 2
    when you define you array, it's outside the for loop you wrote so k doesn't change, hence the last value is always a[k] where k is 9 Commented Jan 5, 2023 at 11:28
  • 1
    also, why do you have a for loop to import numpy each time? Commented Jan 5, 2023 at 11:28
  • @Emi OB can. you correct if possible Commented Jan 5, 2023 at 11:47

1 Answer 1

2
a=[0.1, 0.2, 0.43, 0.44,0.55,0.36,0.57,0.58,0.39,0.40]
k=[[i, j] for i in range(1, 5) for j in range(i + 1, 6)]

print(k)
# [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

for x,y in enumerate(a):
    k[x].append(y)
print(k)

# [[1, 2, 0.1], [1, 3, 0.2], [1, 4, 0.43], [1, 5, 0.44], [2, 3, 0.55], [2, 4, 0.36], [2, 5, 0.57], [3, 4, 0.58], [3, 5, 0.39], [4, 5, 0.4]]

k=np.array(k) #convert to np array
print(k)

array([[1.  , 2.  , 0.1 ],
       [1.  , 3.  , 0.2 ],
       [1.  , 4.  , 0.43],
       [1.  , 5.  , 0.44],
       [2.  , 3.  , 0.55],
       [2.  , 4.  , 0.36],
       [2.  , 5.  , 0.57],
       [3.  , 4.  , 0.58],
       [3.  , 5.  , 0.39],
       [4.  , 5.  , 0.4 ]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.