views:

166

answers:

5

I have read a file in and converted each line into a list. A sample of the list looks like:

['15', '2', '0'], ['63', '3', '445', '456' '0'], ['23', '4', '0']

i want to retrieve the first number from each list and convert it to and integer so when i carry out the type function i.e.

type(x) 
<type 'int'> is returned

Also when i print x the integers are printed individually rather than joined. i.e. if i took the first 3 numbers from the list above the numbers are not printed as:

156323

+1  A: 
# Converts all items in all lists to integers.
ls = [map(int, x) for x in the_first_list]

Or if you just want the first two items:

ls = [map(int, x[:2]) for x in the_first_list]

In python 3.x you'd have to also wrap the map in a list constructor, like this

ls = [list(map(int, x[:2])) ...
Tor Valamo
+1, though not sure if the inner list comprehension is what the OP is looking for. perhaps [map(int, x) for x in the_first_list] ?
Jarret Hardie
This converts all items to integers and keeps the list intact, he just wants the first number of each list.
Kimvais
I changed it slightly to convert it to a list.
Tor Valamo
instead of saying the_first_list shouldn't this read lists[0]
Kimvais
not really. that would, through coincidence, convert only the first list, and the output would be this: [[1, 5], [2], [0]]
Tor Valamo
Wrapping the `map(int, x[:2])` in a `list()` call is redundant in 2.x, since `map()` returns a list. Is this intended to be a 3.x example?
Steve Losh
Yes, I used it in 3.x. Wasn't sure how map works in 2.x, but thanks for clarifying.
Tor Valamo
A: 

If I understood your question correctly, it is [int x[0] for x in list_of_lists]

Kimvais
+2  A: 

If you want a list with the first number of each list, [int(L[0]) for L in lines] (assuming the list of lists is called lines); if you want the first two numbers of each list (it's hard to tell from your question), [int(s) for L in lines for s in L[:2]]; and so forth.

If you don't want a list of such numbers, but just to do one iteration on them, you can use a generator expression, i.e.:

for number in (int(s) for L in lines for s in L[:2]):
  ...do something with number...

or an equivalent nested-loop approach such as:

for L in lines:
  for s in L[:2]:
    number = int(s)
    ...do something with number...
Alex Martelli
+4  A: 

To cast your ints:

my_ints = [int(l[0]) for l in your_list]

To print them out:

print "".join(map(str, my_ints))
Dan Loewenherz
`my_ints = map(lambda n: int(n[0]), your_list)` also works.
Dan Loewenherz
A: 
lines = [['15', '2', '0'], ['63', '3', '445', '456' '0'], ['23', '4', '0']]
first_values_as_ints = [int(line[0]) for line in lines]
for x in first_values_as_ints:
    print x,
Tendayi Mawushe