Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert a normal list to 2d list + changing the values to integers

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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], ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading