【问题标题】:Group continuous numbers in a tuple with tolerance range将具有容差范围的元组中的连续数字分组
【发布时间】:2015-05-23 12:04:48
【问题描述】:

如果我有一组数字:

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

我想以 +/- 3 的公差范围对它们进行分组。

aFunc(locSet)

返回

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

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

【问题讨论】:

  • 可以有多种解决方案。你将如何分组[(10, 20), (12, 20), (14, 20)]

标签: python list range continuous


【解决方案1】:

如果我理解得很好,您正在搜索其值在容差范围内的绝对量不同的元组:[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

这里有两个使用示例:

locSet1 = [(62.5, 121.0), (62.50000762939453, 121.00001525878906), (63.0, 121.0),(63.000003814697266, 121.00001525878906), (144.0, 41.5)]
locSet2 = [(10, 20), (12, 20), (13, 20), (14, 20)]

print aFunc(locSet1)
[[(62.5, 121.0), (144.0, 41.5)]]

print aFunc(locSet2)
[[(10, 20), (12, 20), (13, 20)], [(12, 20), (13, 20), (14, 20)]]

希望对你有所帮助。

【讨论】:

  • @blazinazin215 我的回答有用吗?
猜你喜欢
  • 2013-06-29
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
相关资源
最近更新 更多