I have a tuple of tuples from a MySQL query like this:
T1 = ((\'13\', \'17\', \'18\', \'21\', \'32\'),
(\'07\', \'11\', \'13\', \'14\', \'28\'),
Yet another functional solution for Python 2:
from functools import partial
map(partial(map, int), T1)
Python 3 will be a little bit messy though:
list(map(list, map(partial(map, int), T1)))
we can fix this with a wrapper
def oldmap(f, iterable):
return list(map(f, iterable))
oldmap(partial(oldmap, int), T1)
I would agree with everyones answers so far but the problem is is that if you do not have all integers they will crash.
If you wanted to exclude non-integers then
T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())
This yields only actual digits. The reason I don't use direct list comprehensions is because list comprehension leaks their internal variables.
You can do this with a list comprehension:
T2 = [[int(column) for column in row] for row in T1]
The inner list comprehension ([int(column) for column in row]
) builds a list
of int
s from a sequence of int
-able objects, like decimal strings, in row
. The outer list comprehension ([... for row in T1])
) builds a list of the results of the inner list comprehension applied to each item in T1
.
The code snippet will fail if any of the rows contain objects that can't be converted by int
. You'll need a smarter function if you want to process rows containing non-decimal strings.
If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.
T2 = [parse_a_row_of_T1(row) for row in T1]