将字符串列表转换为整数,但输出是分割数字而不是

时间:2017-10-18 16:48:18

标签: python string list types

所以我有一个string类型的数值列表。列表中的某些元素包含多个数值,例如:

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

我试图将每个元素转换为整数,同时仍保留子列表/元组,所以我希望它看起来像:

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

当我运行以下内容时:

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

我得到了我期望的输出:

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

但是当我尝试通过以下方式将它们变成int时:

       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)

它分别打印出数字:

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

我做错了什么?

3 个答案:

答案 0 :(得分:1)

您不需要for - 循环,因为map已遍历拆分元素:

   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)

或以更紧凑的形式:

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

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

答案 1 :(得分:0)

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

请注意,如果您使用 Python2 ,则无需将map强制转换为list;它已经是list

答案 2 :(得分:0)

一种很好的可读方法是使用列表解析逐步更改列表:

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

或者,组合成一行:

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

然后,如果你想要,你可以打破封闭列表中的单个数字:

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