Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List to integers

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

like image 485
harpalss Avatar asked Oct 22 '25 15:10

harpalss


2 Answers

To cast your ints:

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

To print them out:

print "".join(map(str, my_ints))
like image 167
dwlz Avatar answered Oct 25 '25 03:10

dwlz


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...
like image 30
Alex Martelli Avatar answered Oct 25 '25 03:10

Alex Martelli