views:

158

answers:

3

I have a list containing a tuples and long integers the list looks like this:

   table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]

How do i convert the table to look like a formal list?

so the output would be:

table = ['1','1','1','2','2','2','3','3']

For information purposes the data was obtained from a mysql database.

+6  A: 
>>> table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
>>> [int(e[0]) for e in table]
[1, 1, 1, 2, 2, 2, 3, 3]

>>> [str(e[0]) for e in table]
['1', '1', '1', '2', '2', '2', '3', '3']
Emil Ivanov
Thank you very much :)
Yasmin
You probably also want to know how Emil did it ;) Its a pretty nice python feature called list comprehensions: http://docs.python.org/tutorial/datastructures.html#list-comprehensions
Chris089
+2  A: 

With itertools

import itertools

>>> x=[(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
>>>
>>> list(itertools.chain(*x))
[1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L]
>>>
>>> map(str,itertools.chain(*x))
['1', '1', '1', '2', '2', '2', '3', '3']
S.Mark
A: 

You shouldn't worry about the differences between ints and longs. If you ever try to print a long, the L will disappear.

nums = [1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L]
>>> for num in nums:
...     print num,
1 1 1 2 2 2 3 3

Also, why do you want your result list to have strings? You should keep them as numbers right up until the moment you want to print them. Then you can convert them to strings using string formatting (which is more flexible, too. Especially if you start dealing with floating point or decimal numbers.

>>> print "Your number is: %d" % 1L
Your number is 1
>>> print "If we're talking money, you might want $%.2f" % 2L
If we're talking money, you might want $2.00

Everything will work the way you expect. The L only shows up in the repr of the long, so you know you're working with longs instead of ints.

To get them out of their tuples, you can either do:

>>> nums = [(1L,), (1L,), (2L,), (3L,)]
>>> nums = [x[0] for x in nums]

Which copies your list to a new list, or you can do:

>>> for i, num in enumerate(nums):
...     nums[i] = num

>>> for i in xrange(nums):
...     nums[i] = int(nums[i])

Which will modify your original list rather than creating a new one. In both cases, nums will hold a list of longs.

jcdyer