python - 从元组列表转换为元组列表列表

标签 python

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

我有元组列表,每个元组有两项(元组的数量可能会有所不同)。

[(a, b), (c, d)...)]

我想将列表转换为元组的嵌套列表,以便每个嵌套列表包含 4 个元组,如果原始元组列表的数量不能被 4 整除,例如13 那么最终列表应该包含 13, 1 元组情况下的剩余金额。

[[(a, b), (c, d), (e, f), (g, h)], [(a, b), (c, d), (e, f), (g, h)]...]

关于Python,我喜欢的一件事是在不同数据结构之间进行转换的方法和构造,我希望可能有这样一种方法或构造来解决这个问题,比我想出的更Pythonic。

    image_thumb_pairs = [(a, b), (c, d), (e, f), (g, h), (i, j)]
    row = []
    rows = []
    for i, image in enumerate(image_thumb_pairs):
        row.append(image)
        if(i+1) % 4 == 0:
            rows.append(row)
            row = []
    if row:
        rows.append(row) 

最佳答案

>>> lst = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13, 14), (15, 16), (17, 18)]
>>> [lst[i:i+4] for i in xrange(0, len(lst), 4)]
[[(1, 2), (3, 4), (5, 6), (7, 8)], [(9, 10), (11, 12), (13, 14), (15, 16)], [(17, 18)]]

关于python - 从元组列表转换为元组列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3667581/

相关文章:

python - 在Python中将元组元素切片并堆叠到矩阵中

javascript - 如何通过 python mechanize 中的 javascript 函数模拟 cookie 的设置?

Python字典吃掉了大量的内存

python - Selenium xpath all (//*) 不采用每个 css 元素

python - 如何使用 python-apt API 安装包

Python os.stat 和 unicode 文件名

python - 在 Debian Wheezy 上使用 flask-sqlalchemy 怪异的内存使用和泄漏

python - Python 中的流水线生成器

python - 在单个节点/服务器上使用 Twisted Threading + MapReduce?

python 列表副本 : is there a difference between old[:] and list(old)?