Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python - Can I set a function to call a specific index from a list?

I have n lists (really arrays, but I'm treating them as lists) of length p. I want to pull the first three values from the first, second, and third rows. This is what I have so far:

k0= K[0][0:3]
k1= K[1][0:3]
k2= K[2][0:3]

where

k0= [a,b,c]
k1= [d,e,f]
k2= [g,h,i]

such that

concatenated_ko = []

for j in range(0,3):
    k = "k"+str(j)
    concatenated_ko.append(k)

print(concatenated_ko)

which currently prints

['k0','k1','k2']

but should print

[a,b,c,d,e,f,h,i,j]

Edit: I think what it boils down to is that I initially use an object from <class 'numpy.ndarray'> which changes to <class 'str'>. Forcing a type change from a string to an array by np.ndarray(k) doesn't work either.

Any way to change it back?

question from:https://stackoverflow.com/questions/65928953/can-i-set-a-function-to-call-a-specific-index-from-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've said you "want to pull the first three values from the first, second, and third rows". So instead of creating the three lists k0, k1, and k2 separately, you could put that in your iteration and operate directly on K, by first slicing the first 3 columns.

A.

concatenated_ko = []
for row in K[:3]:
    concatenated_ko.extend(row[:3])

B. or, if you want to use indexes:

concatenated_ko = []
for idx in range(3):
    concatenated_ko.extend(K[idx][:3])

C. And suppose K is a 5x5 array:

>>> K
array([[  5,  12,  10,  70,   4],
       [102,   6, 120,  60,  22],
       [150, 100, 110,   2, 150],
       [ 15,  20,  22,  70,  30],
       [ 20,  55,   1,  70,   1]])

Then to get the first 3 columns of the first 3 rows as a single array, you can use ndarray.flatten():

>>> K[:3, :3].flatten()
array([  5,  12,  10, 102,   6, 120, 150, 100, 110])
>>> K[:3, :3].flatten().tolist()
[5, 12, 10, 102, 6, 120, 150, 100, 110]

Another option, not recommended: To make a minor modification to your original code, use eval to get the list from its variable name, and use extend instead of append:

# with k0, k1, k2 setup as per your question
for j in range(0,3):
    k = "k"+str(j)
    concatenated_ko.extend(eval(k))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...