简体   繁体   中英

split a list of tuples based on the value in the tuple

I have a list which looks like this: Each tuple has a name, start, stop and a direction:

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

which needs to split like this:

    [[('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)]]

There are two rules to split the list: 1) if the abs(start - stop) > 20 between adjacent tuples, make a new list [OR] 2) if the adjacent tuples have opposite direction say ('c',41,50,-1),('d',51,60,+1), make a new list after 'c'

Here is what I have so far:

    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)

For some reason SplitList has an empty list inserted at the end, and I cannot figure out what I have done wrong. Is there a more pythonic approach to do the same?

If it is the first element in the list, add the element to final inside a list then just check the required subelements in the last element of the final list against the current:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM