具有公差范围的元组中连续数的群

2024-09-30 14:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一组数:

locSet = [(62.5, 121.0), (62.50000762939453, 121.00001525878906), (63.0, 121.0),(63.000003814697266, 121.00001525878906), (144.0, 41.5)]

我想把它们分组,公差范围是+/-3。在

^{pr2}$

它回来了

[(62.5, 121.0), (144.0, 41.5)]

我见过Identify groups of continuous numbers in a list,但那是连续整数。在


Tags: ofin整数listgroupscontinuousnumbersidentify
1条回答
网友
1楼 · 发布于 2024-09-30 14:18:01

如果我理解得很好的话,您正在搜索的元组的值在绝对量上的差异在容差范围内:[0,1,2,3]

假设这样,我的解决方案返回一个列表列表,其中每个内部列表都包含满足条件的元组。在

def aFunc(locSet):
  # Sort the list.
  locSet = sorted(locSet,key=lambda x: x[0]+x[1])

  toleranceRange = 3
  resultLst = []
  for i in range(len(locSet)):
      sum1 = locSet[i][0] + locSet[i][1]
      tempLst = [locSet[i]]
      for j in range(i+1,len(locSet)): 
          sum2 = locSet[j][0] + locSet[j][1]
          if (abs(sum1-sum2) in range(toleranceRange+1)):
              tempLst.append(locSet[j])

      if (len(tempLst) > 1):
          for lst in resultLst:
              if (list(set(tempLst) - set(lst)) == []):
                  # This solution is part of a previous solution.
                  # Doesn't include it.
                  break
          else:
              # Valid solution.
              resultLst.append(tempLst)

  return resultLst

这里有两个使用示例:

^{pr2}$

我希望能有所帮助。在

相关问题 更多 >