使用int和None将字符串转换为数组

时间:2019-07-05 23:01:35

标签: python string lambda nonetype

我正在尝试以下代码:

data=str([1, 2, 3, None, None, 4, 5])
temp=data.strip('][').split(', ')
array=list(map(lambda x: None if x==None else int(x), temp))
print(array)

但是我收到此错误:

ValueError: invalid literal for int() with base 10: 'None'

如何获取此信息以将数组放回数组中?谢谢

1 个答案:

答案 0 :(得分:1)

而不是将列表转换为特定于Python的字符串表示形式,而是使用标准(或至少通常使用)的编码(例如JSON)。

lst = [1,2,3, None, None, 4, 5]
data = json.dumps(lst)
assert lst == json.loads(data)