0

I'm trying to use a variable flist consisting of a list of indices to retrieve the elements from features list.

flist = [1, 3, 7]

features = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Desired output:

['b', 'd', 'h']

Is there a way of retrieving the elements from features using flist directly? For example, when I try features[flist[i] for i in range(0,len(flist))] I get an 'invalid syntax' error.

Thanks

immb31
  • 75
  • 1
  • 1
  • 6
  • Note, the linked duplicate is actually asking for *alternatives* to something like `[features[i] for i in flist]`, but that is probably the cleanest way – juanpa.arrivillaga Jan 18 '21 at 18:00

1 Answers1

1
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

idxs = [1, 3, 7]

print ([l[i] for i in idxs])

Output:

['b', 'd', 'h']

Just use a simple list comprehension to make a list of elements from l present at an index contained in idxs.

Synthase
  • 5,849
  • 2
  • 12
  • 34