简体   繁体   中英

Can I access every nth value, for each list a large list?

Python newbie here! I have a list like this:

list_a = [[a,b,c], [d,e,f]]

And I'm trying to find a way to look at only the nth value in each list within the larger list.

ie So both a and d where want the first value in each

I understand I can do this:

  • a -> list_a[0][0]
  • d -> list_a[1][0]

but is there a way I can pull both together to form their own list?

Thanks.

Use list comprehension :

list_a = [['a','b','c'], ['d','e','f']]
n = 1
list_b = [lst[n] for lst in list_a]
print(list_b)
# ['b', 'e']

I would suggest you consider this problem from matrix perspective. That is for your list_a = [['a','b','c'],['d','e',f']], see it as a matrix with two rows and three columns.

Then, what you described as 'nth' value in all sub list is essentially nth columns in this matrix.

Like this

    1   2   3
1   a   b   c
2   d   e   f

Now since you are using 1-D list as the datas structure to represent a 2D matrix, you can only access easily from one direction, regardless you view it as row, or column. That is, a sub list can only represent 'row-direction' or a 'column-direction'

So the idea is to switch the row and column. We call this operation Transpose .( https://en.wikipedia.org/wiki/Transpose )

Row becomes columns, and columns become rows. As the example above, after transposing, the matrix should become:

    1   2
1   a   d 
2   b   e
3   c   f

The corresponding list will become [['a','d'],['b','e'],['c',f']]

Now you can easily access the 'nth columns' (now is nth row) with index, since they are become rows and is a sub-list now.

There are multiple ways to do this.

  1. Using zip() You can use python's builtin function zip() to do the transpose.

     list_a = [['a','b','c'],['d','e','f']] t_list_a = list(zip(*list_a)) t_list_a [('a', 'd'), ('b', 'e'), ('c', 'f')]

Do note that you need to pay attention to the shape of your matrix. That is if all rows (or columns) are in same size or not. Special exception handling might be required.

  1. List comprehension and traditional for loop.

This approach has already been mentioned by other good answers. I will skip it here.

  1. numpy

numpy as a popular library provides very powerful functions to help you with matrix related operation.

    import numpy
    list_a = [['a','b','c'],['d','e','f']]
    t_list_a = numpy.transpose(list_a)
    t_list_a
    array([['a', 'd'],
           ['b', 'e'],
           ['c', 'f']])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM