我有一个列表 lst,如果它们是数字,我想拆分它的元素。所以我的 lst 的格式是这样的:
lst=["1,2,3"," , , ","4,5,6"]
我有一个像下面这样的表达式,但int(i)
如果有一个数字不是空白,我想这样做。我怎样才能做到这一点?提前致谢。
[[int(i) for i in c.split(',')] for c in lst]
我需要的是:
[1, 2, 3, " ", " ", " ", 4, 5, 6]
在得到到做-一切与-列表推导方式:
lst=["1,2,3", " , , ", "4,5,6"]
res = [int(x) if x!=' ' else x for y in lst for x in y.split(',')]
print(res) # [1, 2, 3, ' ', ' ', ' ', 4, 5, 6]
在老学校,为循环方式:
lst=["1,2,3", " , , ", "4,5,6"]
res = []
for item in lst:
if item[0].isdigit():
res.extend(map(int, item.split(',')))
else:
res.extend(item.split(','))
print(res) # [1, 2, 3, ' ', ' ', ' ', 4, 5, 6]
为了清晰起见,我会选择第二个。一看就知道它做了什么。话虽如此,而且您已经编辑了您的需求,毕竟第一个看起来并不那么复杂。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句