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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With