campioni
campioni

Reputation: 157

For loop to extract a item of a sublist / python

I would like to extract one value in each sublist according to the index given by another list.

Here is my code:

lstb = [1, 1, 1, 3]    #give my index

lstc = [['W1', 'w3', 'w4', 'w5'],     
 ['W21', 'w22', 'w23', 'w24'],
 ['W31', 'w32', 'w33', 'w44'],
 ['W51', 'w52', 'w53', 'w54']]        


for i in lstb:
    lstd = []
    for j in lstc:
      l =  lstc[0][i]
      lstd.append(l)

Out[116]: ['w5', 'w5', 'w5', 'w5']

I would like to obtain: [W3,W22,w32,w54]

Could someone help me please?

Thanks!

Upvotes: 1

Views: 360

Answers (3)

kederrac
kederrac

Reputation: 17322

you can use:

lstd = []
for index, num in enumerate(lstc):
      lstd.append(num[lstb[index]])

print(lstd)

output:

['w3', 'w22', 'w32', 'w54']

Upvotes: 0

J...S
J...S

Reputation: 5207

You could use

[elem[ind] for ind, elem in zip(lstb, lstc)]

We use list comprehension and zip() on the list having indices and the list having the target lists.

See zip().

Output would be

['w3', 'w22', 'w32', 'w54']

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Using enumerate

Ex:

>>> lstb = [1, 1, 1, 3]
>>> lstc = [['W1', 'w3', 'w4', 'w5'],     
 ['W21', 'w22', 'w23', 'w24'],
 ['W31', 'w32', 'w33', 'w44'],
 ['W51', 'w52', 'w53', 'w54']]
>>> print([lstc[i][v] for i, v in enumerate(lstb)])
['w3', 'w22', 'w32', 'w54']

Upvotes: 0

Related Questions