could you help me please? I use Python 3.x and would convert this variable ex into an integers list.
ex = [['2003', '12', '27', '7', '8646'],
['2003', '12', '28', '7', '7645'],
['2003', '12', '29', '2', '12823'],
['2003', '12', '30', '2', '14438'],
['2003', '12', '31', '3', '12374']]
I tried with this function but it doesn't work properly:
liste = []
def function_int(x):
for i in x:
liste.append(int[i])
return liste
Thanks you for your support!
You're actually halfway there. You need a nested loop if you want to tackle nested lists .
Something like this.
def function_int(ex):
liste = []
for i in x:
liste.append([])
for j in i:
liste[-1].append(int(i))
return liste
At each outer iteration, we append the next inner list to our outer list. At each inner iteration, append the converted integer value to the most recently appended inner list.
Also note that int
is a function, you call it with parenthesis, not square braces.
Alternatively, you could do this with a list comprehension.
liste = [[int(y) for y in x] for x in ex]
Which is much more concise with minimal loss in readability.
Another possibility is the possiblity of ValueError
s arising during conversion. You could take care of that only if you're working with the nested loop code. You'd use try-except
handlers to do it.
try:
liste[-1].append(int(i))
except ValueError:
pass
Along with the other answers, here is another approach that you can use:
integer_x = [list(map(int, each)) for each in x]
print(integer_x)
take a look at the ast module
you can do this:
import ast
liste = []
for l in ex:
for i in range(len(l)):
l[i] = ast.literal_eval(l[i])
liste.append(l)
Your issue is that ex is a list of lists. So, if you want to put all the ints in ex into the new list you would need two loops:
for i in x:
for j in i:
liste.append(int(j))
this is the fastest most memory efficient way of doing it in my opinion, note: it will overwrite ex
if you want a new list then change ex[:] =
to liste =
or whatever you want to call your variable
try:
#check out this module for faster string checking
from fastnumbers import *
except:
pass
ex = [['2003', '12', '27', '7', '8646'],
['2003', '12', '28', '7', '7645'],
['2003', '12', '29', '2', '12823'],
['2003', '12', '30', '2', '14438'],
['2003', '12', '31', '3', '12374']]
ex[:] = [[int(e) if e.isdigit() else e for e in sl] for sl in ex]
results:
for sublist in ex:
print (sublist)
[2003, 12, 27, 7, 8646]
[2003, 12, 28, 7, 7645]
[2003, 12, 29, 2, 12823]
[2003, 12, 30, 2, 14438]
[2003, 12, 31, 3, 12374]
To explain slice notation, especially being used on the left of =
please see this question: How assignment works with python list slice
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.