问题描述
ls=['ISSN1','94500','2424922X','','21693536','01464116','16879724','22042326','07419341','09272852','00015903','0324721X','']
ls = [i.zfill(8) for i in ls if i != ""]
ls
Output:
['000ISSN1','00094500','0324721X']
方法一:
for i in range(len(ls)):
if ls[i]!="":
ls[i]=str(ls[i]).zfill(8)
else:
pass
ls
方法二:
def changes(ls):
for i in range(len(ls)):
if ls[i]!="":
ls[i]=str(ls[i]).zfill(8)
else:
pass
return ls
ls=changes(ls)
ls
['000ISSN1','']
我仍然想知道是否有一种方法可以通过列表理解实现相同的结果?
解决方法
您可以在推导式中使用条件表达式 (a if condition else b
):
ls = [i.zfill(8) if i else i for i in ls]
请注意,这会将 if i != ""
缩短为 if i
,因为在布尔上下文中只有空字符串为假。
对于您的特定情况,您还可以使用一些技巧(使用 True == 1,False == 0
的事实)使其更短:
ls = [i.zfill(8*bool(i)) for i in ls]
,
见下文
ls = ['ISSN1','94500','2424922X','','21693536','01464116','16879724','22042326','07419341','09272852','00015903','0324721X','']
ls = [i.zfill(8) if i else i for i in ls]
print(ls)
输出
['000ISSN1','00094500','']
,
您只需在代码中添加一个“else”。
ls=['ISSN1','']
ls = [i.zfill(8) if i != "" else '' for i in ls]
ls
输出: