5

我有一个相当最后的数据列表,如下所示:

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我正在尝试压缩它,以便得到这样的东西:

zipped_data = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

我知道我可以做到这一点

l = [(data[0]), (data[1]), (data[2])]
zipped_data = zip(*l)

但我想写一个列表推导来为data. 我试过这个,但它没有用。

s = [zip(i) for i in data]
s
[[(1,), (2,), (3,)], [(4,), (5,), (6,)], [(7,), (8,), (9,)]]

谁能确定我在这里出错的地方?谢谢。

4

3 回答 3

13

尝试*

In [2]: lis=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [3]: zip(*lis)
Out[3]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
于 2012-11-01T16:01:08.280 回答
2

如果您真的想重写zip为列表理解,那么我会这样做:

In [25]: data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [26]: [tuple(lis[j] for lis in data) for j in range(min(len(l) for l in data))]
Out[26]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

In [27]: data = [[1, 2, 3], [4, 5, 6], [7, 8]]

In [28]: [tuple(lis[j] for lis in data) for j in range(min(len(l) for l in data))]
Out[28]: [(1, 4, 7), (2, 5, 8)]

虽然,zip(*data)绝对是解决这个问题的更好方法

于 2012-11-01T16:09:42.470 回答
0

我会这样做,zip但这里是用列表理解完成的

def zip_lists(lists):
    """
        Assuming all lists have the same length

        >>> zip_lists([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

        >>> zip_lists([[1, 2], [3, 4], [5, 6], [7, 8]])
        [[1, 3, 5, 7], [2, 4, 6, 8]]

    """
    return [[l[x] for l in lists] for x in range(len(lists[0]))]
于 2012-11-01T16:10:13.300 回答