如何使用 Python 中的列表理解将空元素保留在列表中?

问题描述

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

输出:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...