簡體   English   中英

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

[英]Double all columns except for the first and the last one

我想從一個數據結構,如:

[[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] 

但我想知道是否有更優雅,更易讀的方式來寫這個。

我想知道是否有更優雅,更易讀的方式來寫這個。

我認為你還應該考慮“更具可讀性”並不一定意味着“是否有可能把它塞進一行?”。 它通常意味着更明確和直接的迭代代碼。 也許您可能會發現此函數更具可讀性:

>>> 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]
>>> 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]]

鑒於你的名單

>>> 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM