2014-11-04 39 views
1

我有一个列表,它看起来像这样: 每个元组都有一个名字,启动,停止和方向:拆分基于元组的值元组的列表

major_list = [('a',20,30,-1),('b',31,40,-1),('c',41,50,-1),('d',51,60,+1),('z',90,100,-1),('e',61,70,+1),('f',71,80,+1)] 

这就需要分割像此:

[[('a',20,30,-1),('b',31,40,-1),('c',41,50,-1)],[('d',51,60,+1)],[('z',90,100,-1)],[('e',61,70,+1),('f',71,80,+1)]] 

有两个规则分裂列表: 1)如果ABS(开始 - 停止)相邻的元组之间的> 20,使一个新的列表[OR] 2)如果相邻元组具有相反的方向说('c',41,50,-1),('d',51,60,+ 1),做一个新的“C”

这里后列表是我到目前为止有:

SplitList = [] 
    for i,tup in enumerate(major_List): 
     if i != len(major_List)-1: 
      if i == 0: 
       tmp_list = [] 
      next_tup = major_List[i+1] 
      if (abs(int(next_tup[1]) - int(tup[2])) > 20) or (next_tup[3] != tup[3]): 
       tmp_list.append(tup) 
       if tmp_list:     
       SplitList.append(tmp_list) 
       tmp_list = [] 
     else: 
      tmp_list.append(tup) 

出于某种原因SplitList在末端插入一个空的列表,我想不出什么我做错了。是否有更多pythonic方法来做同样的事情?

+0

让我看看我正确地理解了这个问题:你需要一个带有两个列表的列表:第一个列表的方向为-1,第二个列表的方向为+1的对象? – 2014-11-04 21:51:03

+0

否根据规则(其中2个)原始列表将被拆分成子列表;因此结果列表将是各种列表的列表 – user2998764 2014-11-04 21:56:26

回答

2

如果是在列表中的第一个元素,该元素添加到final列表里面,然后只检查所需的子元素中final列表针对当前的最后一个元素:

major_list = [('a',20,30,-1),('b',31,40,-1),('c',41,50,-1),('d',51,60,+1),('z',90,100,-1),('e',61,70,+1),('f',71,80,+1)] 

final = [] 

for ele in major_list: 
    if not final: 
     final.append([ele]) # final is empty so add the first element in a list 
    # check the last item of the last sublist added to final and compare to our current element 
    elif abs(final[-1][-1][1] - ele[2]) > 20 or final[-1][-1][3] != ele[3]: 
    # if it does not meet the requirement, add it to final in a new list 
     final.append([ele]) 
    else: 
     # else add it to the last sublist 
     final[-1].append(ele) 
print(final) 

[[('a', 20, 30, -1), ('b', 31, 40, -1), ('c', 41, 50, -1)], [('d', 51, 60, 1)], [('z', 90, 100, -1)], [('e', 61, 70, 1), ('f', 71, 80, 1)]]