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

11,024

Solution 1

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]
    

Solution 2

I'll chime in with the numpy solution

import numpy
t = ((1,2,3),(3,4,5),(1,4,5),(9,8,7))
x = 6
col_id = 2

a = numpy.array(t)
print a[a[:,col_id] == x]
Share:
11,024
misterrobinson
Author by

misterrobinson

CTO, CEO, and software developer for 20+ years Currently loving Python, PHP, AJAX, and all things web and mobile.

Updated on June 26, 2022

Comments

  • misterrobinson
    misterrobinson about 2 years

    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.