2017-02-16 40 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)]