用于在列表中创建给定数量元素的 Python 习惯用法
通常,当我使用 Python 时,我会发现自己编写的列表推导式看起来像这样:
num_foobars = 10
foobars = [create_foobar() for idx in xrange(num_foobars)]
显然,这工作得很好,但当我创建一个范围并在其中迭代虚拟索引时,我仍然感觉有点尴尬。我实际上根本没有使用该信息。
我一点也不关心性能或类似的事情,它只是感觉不像 Python 通常那样优雅。
我想知道是否有任何好的惯用方法来避免列表理解语法中不必要的部分,也许使用诸如 map
之类的东西或 itertools
中的东西,给我看起来像的代码更像...
num_foobars = 10
foobars = repeat(create_foobar, num_foobars)
Often when I'm using Python I'll find myself writing list comprehensions that look something like this:
num_foobars = 10
foobars = [create_foobar() for idx in xrange(num_foobars)]
Obviously that works just fine, but it still feels a little awkward to me to creating a range and iterating dummy index across it, when I'm not actually using that information at all.
I'm not in any way concerned about performance or anything like that, it just doesn't feel quite as wonderfully elegant as Python usually does.
I'm wondering if there's any nice idiomatic way to avoid the unnecessary bits of list comprehension syntax, perhaps using something like map
or something in itertools
, to give me code that looks more like...
num_foobars = 10
foobars = repeat(create_foobar, num_foobars)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 itertools 方式:
itertools 方式又短又快。也就是说,我更喜欢列表理解:-)
Here is the itertools way:
The itertools way is short and fast. That said, I prefer the list comprehension :-)
在
create_foobar
接受参数的情况下,只需迭代参数列表即可。正如or
但在
create_foobar
不带参数的特殊情况下,我想你可以这样做:lambda 有点难看;呼应 Raymond Hettinger 的观点,我认为标准列表理解更可取。还值得注意的是,这会创建一个相当长且无用的列表来迭代,这是标准方法所避免的。您可以通过使用 itertools.repeat 创建一个 Foobar 的迭代来解决这个问题...这会增加更多的复杂性。
更一般地说,考虑一下:如果您没有迭代任何东西,则必须有一个索引变量,即使它是隐藏的;并且显式优于隐式。
In cases where
create_foobar
accepts an argument, it's just a matter of iterating over a list of arguments. As inor
But in the special case that
create_foobar
takes no arguments, I suppose you could do something like this:The lambda is a bit ugly though; echoing Raymond Hettinger's sentiments, I think the standard list comprehension is preferable. It's also worth noting that this creates a rather long and useless list to iterate over, which the standard approach avoids. You could fix that by using
itertools.repeat
to create an iterable ofFoobar
s... adding even more complication.More generally, consider this: if you aren't iterating over anything, there has to be an index variable, even if it's hidden; and explicit is better than implicit.
您可以定义函数
repeat
,但惯用的编写方式仍然是“抱歉”。我同意基于
xrange
的构造通常看起来很难看,但这就是该语言的工作方式。You could define the function
repeat
, but the idiomatic way to write it would still beSorry about that. I agree that
xrange
-based constructs often look ugly, but it's just how the language works.;c)
;c)