开发者

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开发者_JS百科


To cast your ints:

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

To print them out:

print "".join(map(str, my_ints))


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...


# 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])) ...


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


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,
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜