每日小知识:python列表解析
列表解析的语法为: [表达式 + 上下文]
直接举个例子
运行下列代码
print([x.lower() for x in ['I', 'AM', 'ROBOT']])
# 结果 ['i', 'am', 'robot']
这里表达式为 x.lower()
, 上下文为 for x in ['I', 'AM', 'ROBOT']
这行代码所做的事情,就是把['I', 'AM', 'ROBOT']
中的每一个元素变为小写。
再举个稍微复杂的例子
text = '''
It is said that the true nature of being is veiled.
The labor of words, the expression of art,
the seemingly ceaseless buzz that is human
thought all have in common the need to get at what really is so.
The hope to draw close to and possess the truth of being can be a feverish one.
In some cases it can even be fatal,
if pleasure is one's truth and its attainment more important than life itself.
In other lives, though, the search for what is truthful gives life.
'''
w = [[x for x in line.split() if len(x) > 3] for line in text.split('\n')]
# w为[[], ['said', 'that', 'true', 'nature', 'being', 'veiled.'], ['labor', 'words,', 'expression', 'art,'], ['seemingly', 'ceaseless', 'buzz', 'that', 'human'], ['thought', 'have', 'common', 'need', 'what', 'really'], ['hope', 'draw', 'close', 'possess', 'truth', 'being', 'feverish', 'one.'], ['some', 'cases', 'even', 'fatal,'], ['pleasure', "one's", 'truth', 'attainment', 'more', 'important', 'than', 'life', 'itself.'], ['other', 'lives,', 'though,', 'search', 'what', 'truthful', 'gives', 'life.'], []]
代码w = [[x for x in line.split() if len(x) > 3] for line in text.split('\n')]
就是列表解析(有些地方也叫列表推导)
分析一下这行代码,它首先将text
中的每一行分割开,然后内层的列表解析对每一行的代码再次按照空格分割,并加以条件判断,只有长度大于3的单词才被加入列表中。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!