根据元组中的值拆分元组列表

时间:2014-11-04 21:47:26

标签: python list tuples

我有一个如下所示的列表: 每个元组都有一个名称,开始,停止和方向:

    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方法来做同样的事情?

1 个答案:

答案 0 :(得分: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)]]