Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 3rd, 2012  |  syntax: None  |  size: 0.65 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Python List Slicing with Arbitrary Indices
  2. a = range(100)
  3. s = [a[i] for i in [5,13,25]]
  4.        
  5. a = 0:99;
  6. s = a([6,14,26])
  7.        
  8. >>> from operator import itemgetter
  9. >>> a = range(100)
  10. >>> itemgetter(5,13,25)(a)
  11. (5, 13, 25)
  12.        
  13. In [37]: import numpy as np
  14.  
  15. In [38]: a = np.arange(100)
  16.  
  17. In [39]: s = a[[5,13,25]]
  18.  
  19. In [40]: s
  20. Out[40]: array([ 5, 13, 25])
  21.        
  22. class MyList(list):
  23.     def __getitem__(self, index):
  24.         if not isinstance(index, tuple):
  25.             return list.__getitem__(self, index)
  26.         return [self[i] for i in index]
  27.        
  28. >>> m = MyList(i * 3 for i in range(100))
  29. >>> m[20, 25,60]
  30. [60, 75, 180]
  31.        
  32. a = list(range(99))
  33.     s = [a[5], a[13], a[25]]