-1

I need to convert a list of strings into integers.

Example: [['1,2'],['3,4']]

The desired result would be [[1,2],[3,4]]

I tried using a for loop however nothing was changed

Barmar
  • 669,327
  • 51
  • 454
  • 560

3 Answers3

0

For all sublist, if you want [['1,2'], ['3,4', '5,6']] > [[1, 2], [3, 4], [5, 6]]

For in-place replacement:

This solution doesn't create a new list.

old_list = [['1,2'], ['3,4']]

for elem in old_list:
    tmp = elem[0].split(',')
    elem.clear()
    elem.extend(int(n) for n in tmp)

print(old_list)  # [[1, 2], [3, 4]]

If you want to create a new list:

old_list = [['1,2'], ['3,4']]

new_list = [
    [int(n) for n in tmp_2.split(",")]
    for tmp_1 in old_list
    for tmp_2 in tmp_1
]

print(new_list)  # [[1, 2], [3, 4]]

For all sublist, if you want [['1,2'], ['3,4', '5,6']] > [[1, 2], [3, 4, 5, 6]]

For in-place replacement:

src = [['1,2'], ['3,4', '5,6']]

for elem in src:
    tmp = ','.join(elem).split(',')
    elem.clear()
    elem.extend(int(n) for n in tmp)

print(src)  # [[1, 2], [3, 4, 5, 6]]

If you want to create a new list:

old_list = [['1,2'], ['3,4', '5,6']]

new_list = [
    [int(n) for n in ','.join(tmp_1).split(',')]
    for tmp_1 in old_list
]

print(new_list)  # [[1, 2], [3, 4, 5, 6]]
Dorian Turba
  • 1,818
  • 3
  • 20
  • 33
-1

You can try using a comprehensive list like this.

numbers = [
    list(map(int, expand_list2.split(",")))
    for expand_list1 in [['1,2'],['3,4']]
    for expand_list2 in expand_list1
]

This might help explain the above a little better https://www.w3schools.com/python/python_lists_comprehension.asp

mRyan
  • 178
  • 2
  • 17
-1
main_arr = [['1,2'],['3,4']]
xx = [list(map(int, ','.join(sub_arr).split(',')))  for sub_arr in main_arr]
print(xx)

output

[[1, 2], [3, 4]]

or

xx = list(map(lambda x: list(map(int, ','.join(x).split(','))), main_arr))

or

for i, v in enumerate(main_arr):
     tmp = []
     for idx, val in enumerate(v):
             tmp.extend([int(ij) for ij in val.split(',')])
     main_arr[i] = tmp
sahasrara62
  • 7,680
  • 2
  • 24
  • 37