python range() 有重复项?
每个人都知道可以使用 range
获取数字列表,如下所示;:
>>> list(range(5))
[0, 1, 2, 3, 4]
如果您想要每个数字的 3 个副本,则可以使用:
>>> list(range(5)) * 3
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
但是有没有一种简单的方法使用 range< /code> 像这样重复复制?
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
示例:
sorted(list(range(5)) * 3) # has unnecessary n * log(n) complexity
[x//3 for x in range(3*5)] # O(n), but division seems unnecessarily complicated
Everybody knows that a list of numbers can be obtained with range
like this;:
>>> list(range(5))
[0, 1, 2, 3, 4]
If you want, say, 3 copies of each number you could use:
>>> list(range(5)) * 3
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
But is there an easy way using range
to repeat copies like this instead?
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Examples:
sorted(list(range(5)) * 3) # has unnecessary n * log(n) complexity
[x//3 for x in range(3*5)] # O(n), but division seems unnecessarily complicated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以这样做:
range(3)
部分应替换为您的重复次数...顺便说一句,您应该使用生成器
只是为了使其更清楚,
_
是您不关心的变量名称(允许任何名称)。此列表理解使用嵌套的
for
循环,就像这样:You can do:
the
range(3)
part should be replaced with your number of repetitions...BTW, you should use generators
Just to make it clearer, the
_
is a variable name for something you don't care about (any name is allowed).This list comprehension uses nested
for
loops and are just like that:试试这个:
Try this:
离开
列表,你就拥有了一台发电机。
编辑:甚至更好(省略对 izip 的函数调用):
Gives
Leave off the list and you have a generator.
EDIT: or even better (leaves out a function call to izip):
在 numpy 的帮助下,有一种非常简单的方法可以做到这一点。示例:
使用 range,您可以执行以下操作:
记住 // 执行严格的整数除法。
There is a very simple way to do this with a help from numpy. Example:
With range you can do the following:
Remembering that // performs a strict integer division.
使用另一种方法的很酷的迭代器:
A cool iterator using another approach:
我喜欢保持简单:)
I like to Keep It Simple :)
或者:
Or: