Python, comparison sublists and making a list

后端 未结 2 518
无人共我
无人共我 2021-01-22 10:57

I have a list that contains a lot of sublists. i.e.

mylst = [[1, 343, 407, 433, 27], 
         [1, 344, 413, 744, 302], 
         [1, 344, 500, 600, 100], 
              


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-22 11:17

    This seems to have worked for me. I'm not sure if its more Pythonic in any way though and you'll be looping through the list multiple times so there's some things you can definitely do to optimize it more.

    def seg(mylist):
        # converted list to set in case there are any duplicates
        segments = set()
    
        for entry_index in range(len(mylist)):
            for c in range(len(mylist)):
                first = mylist[entry_index]
                comparison = mylist[c]
    
                # ignore comparing the same items
                if entry_index == c:
                   continue
    
                # ignore cases where the first item does not match
                if first[0] != comparison[0]:
                    continue
    
                # ignore cases where the second item differs by more than 2
                if abs(first[1] - comparison[1]) > 2:
                    continue
    
                # add cases where the third and fourth items differ by less than 10
                if abs(first[2] - comparison[2]) < 10 or abs(first[3] - comparison[3]) < 10:
                    segments.add(entry_index)
    
                elif abs(first[2] - comparison[3]) < 10 or abs(first[3] - comparison[2]) < 10:
                    segments.add(entry_index)
    
        return segments
    

提交回复
热议问题