1

Is there a way to select every 2nd or 3rd (for example) item within a matrix?

For example:

f = [["1", "5", "8", "9"], ["2", "6", "9", "10"], ["3", "7", "11", "12"]]

I am wondering if there is a direct function to select every 2nd number in every list (preferably putting those digits in a list as well). Thus resulting into:

["5", "6", "7"]

I know that I can achieve this using a loop but I am wondering if I can achieve this directly.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
SecondLemon
  • 953
  • 2
  • 9
  • 18
  • There is already an answer for tuples here: http://stackoverflow.com/questions/2054416/getting-the-first-elements-per-row-in-an-array-in-python – MonteCarlo Feb 26 '15 at 18:37

3 Answers3

5

Without any loop (external)

>>> f = [["1", "5", "8", "9"], ["2", "6", "9", "10"], ["3", "7", "11", "12"]]
>>> list(map(lambda x:x[1],f))  # In python2, The list call is not required
['5', '6', '7']

Ref : map

Another way to do it without loop (Courtesy : Steven Rumbalski)

>>> import operator
>>> list(map(operator.itemgetter(1), f))
['5', '6', '7']

Ref: itemgetter

Yet another way to do it without loop (Courtesy : Kasra A D)

>>> list(zip(*f)[1])
['5', '6', '7']

Ref: zip

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    Just Note: A list comp is more pythonic in a few cases, though not in most cases ... http://stackoverflow.com/a/1247490/4099593 ... However as you mention *I know that I can achieve this using a loop but I am wondering if I can achieve this directly.* `map` is the only way you can do to get your job done without using any loop! – Bhargav Rao Feb 26 '15 at 18:40
  • 1
    Agreed. A list comp is best. Also an available option `list(map(operator.itemgetter(1), f))`. If using Python 2 the call to `list()` can be omitted. – Steven Rumbalski Feb 26 '15 at 18:45
  • @StevenRumbalski Yep, But I always insist on having the `list` call, just in case a future user tries this! – Bhargav Rao Feb 26 '15 at 18:47
  • 1
    you can add `zip` to collection of solutions ;) : `>>> zip(*f)[1] ('5', '6', '7') ` – Mazdak Feb 26 '15 at 18:53
5

Try list comprehension:

seconds = [x[1] for x in f]
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
0

You may use list comprehension:

i = 1  # Index of list to be accessed
sec = [s[i] for s in f if len(s) > i]

This code will also check in each sublist whether the index is a valid value or not.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126