将所有列加倍,除了第一列和最后一列

时间:2012-05-04 08:59:25

标签: python list-comprehension

我想从以下数据结构出发:

[[0,   12,  25,  45,  65,  100],
 [0,   0,   0,   255, 255, 255],
 [0,   0,   255, 255, 0,   0],
 [255, 255, 0,   0,   0,   0]]

为:

[[0,   12,  12, 25,   25,  45,  45,  65,  65, 100],
 [0,   0,   0,   0,   0,   255, 255, 255, 255, 255],
 [0,   0,   0,   255, 255, 255, 255, 0,   0,   0],
 [255, 255, 255, 0,   0,   0,   0,   0,   0,   0]]

(重复除第一列和最后一列之外的所有列。)

我有以下列表理解有效:

[[l[0]] + [x for sl in [[i, i] for i in l[1:-1]] for x in sl] + [l[-1]] for l in list_of_lists] 

但我想知道是否有更优雅,更易读的方式来写这个。

3 个答案:

答案 0 :(得分:2)

  

我想知道是否有更优雅,更易读的方式来写这个。

我认为你还应该考虑“更具可读性”并不一定意味着“是否有可能把它塞进一行?”。它通常意味着更明确和直接的迭代代码。也许您可能会发现此功能更具可读性:

>>> def double_middle_items(l):
        if len(l) < 2:
            raise ValueError("there must be at least two items in l")

        result = [l[0]]
        for item in l[1:-1]:
            result.append(item)
            result.append(item)
        result.append(l[-1])
        return result

>>> double_middle_items([1,2,3,4,5])
[1, 2, 2, 3, 3, 4, 4, 5]

然后你的代码变得非常简单:

>>> [double_middle_items(l) for l in list_of_lists]

答案 1 :(得分:2)

>>> from itertools import chain
>>> data = [[0,   12,  25,  45,  65,  100], [0,   0,   0,   255, 255, 255], [0, 0, 255, 255, 0,   0], [255, 255, 0,   0,   0,   0]]
>>> [list(chain.from_iterable(zip(l,l[1:]))) for l in data]
[[0, 12, 12, 25, 25, 45, 45, 65, 65, 100], [0, 0, 0, 0, 0, 255, 255, 255, 255, 255], [0, 0, 0, 255, 255, 255, 255, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0, 0, 0]]

答案 2 :(得分:2)

将您的清单列为

>>> spam=[[0,   12,  25,  45,  65,  100],
 [0,   0,   0,   255, 255, 255],
 [0,   0,   255, 255, 0,   0],
 [255, 255, 0,   0,   0,   0]]

您可以链接列表中每个元素的重复

>>> from itertools import repeat,chain
>>> [list(chain(*([i]*2 for  i in r)))[1:-1]  for r in spam]
[[0, 0, 12, 12, 25, 25, 45, 45, 65, 65, 100, 100], [0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255], [0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0], [255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0]]

或使用重复

>>> [list(chain(*(repeat(i,2) for  i in r)))[1:-1]  for r in spam]