将长元组拆分为较小的元组
我有一个很长的元组
(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)
,我想把它分成一个元组的元组,就像
((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10))
我是Python新手一样,我不太擅长元组 o(2, 2, 10, 10, 344, 344, 45, 43, 2 , 2, 10, 10, 12, 8, 2, 10)r 列表。我的朋友说我应该拆分它,但我就是无法得到它 -_-
我需要将元组拆分为具有 4 个元素的元组,稍后我将使用矩形将其绘制到带有 PIL 的图像上。
I have a long tuple like
(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)
and i am trying to split it into a tuple of tuples like
((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10))
I am new to python and am not very good with tuples o(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)r lists. My friend said i should split it but i just cant get it -_-
I need to split the tuple into tuples with 4 elements that i will later use a rectangles to draw to a image with PIL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
嗯,有一个特定的成语:
但解释起来有点复杂。 itertools 收据中列出了一个稍微更通用的版本。
您也可以自己对元组进行切片
,这可能就是您朋友的意思。
Well there is a certain idiom for that:
But its kind of complicated to explain. A slightly more general version of this is listed in the itertools receipes.
You can also slice the tuple yourself
which is probably what your friend meant.
另一个可能的答案(使用生成器):
Another possible answer (using a generator):
我之前写过一个像 gist 这样的函数,可以在 http://gist.github.com/616853
代码比上面给出的解决方案要长,但涵盖了所有可能的序列分割条件。
I had written such a function as gist some time back, available at http://gist.github.com/616853
The code is longer than the solutions given above, but covers all possible sequence split conditions.
您可以使用
dollop
包 (pip install dollop
) 来完成此操作:输出:
You can do this using the
dollop
package (pip install dollop
):Output: