0

So I have a list of numerical values that are of type string. Some of the elements of the list contain more than one numerical value, for instance:

AC_temp= ['22', '45, 124, 12', '14', '12, 235']

I'm trying to turn each of these elements into integers, while still conserving the sub-lists/tuples, so I want it to look like:

AC_temp=[22, [45, 124, 12], 14, [12, 235]]

When I run the following:

       for x in AC_temp:
           if "," in x: #multiple values
              val= x.split(",")
              print(val)

I get the output I expect:

 ['187', '22']
 ['754', '17']
 ['417', '7']
 ['819', '13']
 ['606', '1']
 ['123', '513']

But then when I try to turn them into ints via the following:

       for x in AC_temp:
           if "," in x:
              val= x.split(",")
              for t in val:
                  AC.append(map(int, t))
           else:
              AC.append(map(int, x)

       #print output#
       for i in AC:
           print(i)

It prints out the digits separately as such:

[1, 8, 7]
[2, 2]
[7, 5, 4]
[1, 7]
[4, 1, 7]
[7]
[8, 1, 9]
[1, 3]
[6, 0, 6]
[1]
[1, 2, 3]
[5, 1, 3]

What am I doing wrong?

claudiadast
  • 419
  • 1
  • 9
  • 18
  • Possible duplicate of [How to convert strings into integers in Python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) – scharette Oct 18 '17 at 16:52

3 Answers3

1

You don't need the for-loop, because map already iterates over the splitted elements:

   AC = []
   for x in AC_temp:
       if "," in x:
          val= x.split(",")
          AC.append(list(map(int, val))
       else:
          AC.append([int(x)])

   #print output#
   for i in AC:
       print(i)

or in a more compact form:

   AC = [list(map(int, x.split(","))) for x in AC_temp]

   #print output#
   for i in AC:
       print(i)
Ma0
  • 15,057
  • 4
  • 35
  • 65
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

How about a list-comprehension?

AC_temp= ['22', '45, 124, 12', '14', '12, 235']

AC = [int(x) if ',' not in x else list(map(int, x.split(','))) for x in AC_temp]
print(AC)  # [22, [45, 124, 12], 14, [12, 235]]

Note that if you are using Python2, you do not need to cast the map to list; it is already a list.

Ma0
  • 15,057
  • 4
  • 35
  • 65
0

A nice readable way to do this is to gradually change the list using list comprehension:

AC_temp= ['22', '45, 124, 12', '14', '12, 235']

individual_arrays = [i.split(", ") for i in AC_temp]
# ...returns [['22'], ['45', '124', '12'], ['14'], ['12', '235']]

each_list_to_integers = [[int(i) for i in j] for j in individual_arrays]
# ...returns [[22], [45, 124, 12], [14], [12, 235]]

or alternatively, combined into one line:

numbers_only = [[int(i) for i in j] for j in [i.split(", ") for i in AC_temp]]

Then if you want you can break the single numbers out of their enclosing lists:

no_singles = [i[0] if len(i) == 1 else  i for i in each_list_to_integers]