Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use python slicing to access one "column" of a nested tuple?

Tags:

python

slice

I have a nested tuple that is basically a 2D table (returned from a MySQL query). Can I use slicing to get a list or tuple of one "column" of the table?

For example:

t = ((1,2,3),(3,4,5),(1,4,5),(9,8,7))

x = 6

How do I efficiently check whether x appears in the 3rd position of any of the tuples?

All the examples of slicing I can find only operate within a single tuple. I don't want to slice a "row" out of t. I want to slice it the other way -- vertically.

like image 686
misterrobinson Avatar asked Apr 02 '13 22:04

misterrobinson


1 Answers

Your best bet here is to use a generator expression with the any() function:

if any(row[2] == x for row in t):
    # x appears in the third row of at least one tuple, do something

As far as using slicing to just get a column, here are a couple of options:

  • Using zip():

    >>> zip(*t)[2]
    (3, 5, 5, 7)
    
  • Using a list comprehension:

    >>> [row[2] for row in t]
    [3, 5, 5, 7]
    
like image 133
Andrew Clark Avatar answered Nov 14 '22 23:11

Andrew Clark