I want to convert a normal list to 2d list and want to change the numbers to integers instead of str
I have somthing like this
my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']
I want somthing like this using for loop:
my_list = [[00000000], [00000000], [00111000], [00101000], [00101000], [00000000], [00000000], [00000000]]
>Solution :
You may use a list comprehension here:
my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']
output = [[int(x)] for x in my_list]
print(output) # [[0], [0], [111000], [101000], [101000], [0], [0], [0]]
Note that there is no Python integer literal 00000000
, which is really the same as 0
. If you need the leading zeroes, then you should leave your data as strings.
Edit:
To get a 2D list of single numbers from each string, use:
my_list = ['00000000', '00000000', '00111000', '00101000', '00101000', '00000000', '00000000', '00000000']
output = [[int(x) for x in list(y)] for y in my_list]
print(output)
# [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 1, 1, 1, 0, 0, 0], ...