2017-02-16 56 views
1

組我有一個像清單元組

A = [1,10,50,100,500] 

我需要按2號與正確的順序清單。輸出是這樣的,

B = [(1,9),(10,49),(50,99),(100,499)] 

我已經通過yield嘗試:

def group(lst, n): 
    for i in range(0, len(lst), n): 
     val = lst[i:i+n] 
     if len(val) == n: 
      yield tuple(val) 

print(list(group([1,10,50,100,500], 2))) 
+0

您確定不應該使用'bisect'嗎? –

回答

1

你可以簡單地zip與本身的序列(不含第一項):

A = [1,10,50,100,500] 

def group(lst): 
    for i, j in zip(A, A[1:]): # pairwise items 
     yield (i, j-1)   # decrement second item by 1 

>>> list(group(A)) 
[(1, 9), (10, 49), (50, 99), (100, 499)] 

或者用它作爲沒有中間功能的列表理解:

>>> [(i, j-1) for i, j in zip(A, A[1:])] 
[(1, 9), (10, 49), (50, 99), (100, 499)] 
0

您可以使用列表理解與islicezip在列表上迭代成對:

>>> from itertools import islice 
>>> A = [1,10,50,100,500] 
>>> [(x, y - 1) for x, y in zip(A, islice(A, 1, None))] 
[(1, 9), (10, 49), (50, 99), (100, 499)] 

在上面islice返回從A第二個元素開始的迭代器。 islice用於正常切割代替原來的名單並不需要被複制:

>>> s = list(islice(A, 1, None)) 
>>> s 
[10, 50, 100, 500] 

然後zip用於從原始列表和迭代器創建可迭代的項目配對:

>>> pairs = list(zip(A, s)) 
>>> pairs 
[(1, 10), (10, 50), (50, 100), (100, 500)] 

最後,列表理解迭代對來創建結果:

>>> [(x, y - 1) for x, y in pairs] 
[(1, 9), (10, 49), (50, 99), (100, 499)]