0

I'm looking for a way to access an object multiple times in an easy way.

Ex. 1)

ls = [i for i in range(100)]; print(ls[0], ls[32], ls[95])

Ex. 2)

js = {'key0': 'val0', ...}; print (js['keyN'], js['keyM'])

What I'm looking for is a way to only specify the object once, and then specify the wanted indices (something like slice). Meaning ls[0,32,95], or js['keyN][inner_keyN_M, innerkeyN_M+3]

locke14
  • 1,335
  • 3
  • 15
  • 36
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

1 Answers1

2

You can use the itemgettermodule.

from operator import itemgetter
ls = [i for i in range(100)]
ids = [0, 32, 95]
print(itemgetter(*ids)(ls))

Output

(0, 32, 95)

You can also use list comprehension:

ls = [i for i in range(100)]
ids = [0, 32, 95]

print([ls[id] for id in ids])
locke14
  • 1,335
  • 3
  • 15
  • 36