具有重复函数调用的列表理解 [英] List comprehension with duplicated function call

查看:35
本文介绍了具有重复函数调用的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要转换如下字符串:

'   1   ,   2  ,    ,   ,   3   '

进入非空元素列表:

['1', '2', '3']

我的解决方案是这个列表理解:

My solution is this list comprehension:

print [el.strip() for el in mystring.split(",") if el.strip()]

想知道,是否有一种不错的,pythonic的方式来编写这种理解,而无需两次调用 el.strip()?

Just wonder, is there a nice, pythonic way to write this comprehension without calling el.strip() twice?

推荐答案

您可以在列表推导中使用生成器:

You can use a generator inside the list comprehension:

  [x for x in (el.strip() for el in mylist.split(",")) if x]
#             \__________________ ___________________/
#                                v
#                        internal generator

因此,生成器将提供剥离后的元素,我们迭代生成器,仅检查真实性.因此,我们节省了 el.strip()调用.

The generator thus will provide stripped elements, and we iterate over the generator, and only check the truthiness. We thus save on el.strip() calls.

您还可以使用 map(..)为此(使其更具功能):

You can also use map(..) for this (making it more functional):

  [x for x in map(str.strip, mylist.split(",")) if x]
#             \______________ ________________/
#                            v
#                           map

但这基本上是相同的(尽管我认为生成器的逻辑更好地封装了).

But this is basically the same (although the logic of the generator is - in my opinion - better encapsulated).

这篇关于具有重复函数调用的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆