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
Solution 1:
To cast your ints:
my_ints = [int(l[0]) for l in your_list]
To print them out:
print"".join(map(str, my_ints))
Solution 2:
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.:
fornumberin (int(s) forLin lines forsin L[:2]):
...do something with number...
or an equivalent nested-loop approach such as:
for L inlines:
for s in L[:2]:
number = int(s)
...do something withnumber...
Solution 3:
# 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])) ...
Solution 4:
If I understood your question correctly, it is [int x[0] for x in list_of_lists]
Solution 5:
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,
Post a Comment for "Python: List To Integers"