[英]Turning list of strings into integers, but output is splitting digits instead of
因此,我有一个字符串类型的数值列表。 列表中的某些元素包含多个数值,例如:
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']
但是,当我尝试通过以下方法将它们转换为整数时:
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]
我究竟做错了什么?
您不需要for
-loop,因为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)
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
。
一种不错的可读方法是使用列表理解逐步更改列表:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.