【问题标题】:Remove similar numbers in a list删除列表中的相似数字
【发布时间】:2016-09-17 06:54:48
【问题描述】:

如何从以下列表中删除 86.1 和 90.1(或 86.2 和 90.2)之类的数字?

86.1      86.2       90.1      90.2

【问题讨论】:

  • 听不懂你在问什么?
  • 定义一个容差值为tolerance = 3,现在将每个元素除以这个值,然后再次乘以相同的值,现在使用set得到想要的结果
  • 你如何定义相似?如果两个相似,哪一个会被删除?

标签: python list python-2.7


【解决方案1】:

定义一个阈值,遍历排序后的数字并将阈值内的数字相加:

numbers = [86.1, 86.2, 90.1,90.2]

threshold = 1
numbers = iter(numbers)
amount = last = next(numbers)
count = 1
result = []
for number in sorted(numbers):
    if number - last > threshold:
        result.append(amount/count)
        amount = count = 0
    amount += number
    count += 1
    last = number

result.append(数量/计数)

【讨论】:

    【解决方案2】:

    试试这个:

    base = [86.1, 86.2, 90.1, 90.2]
    # remove = [86.2, 90.2]
    remove = [86.1, 90.1]
    
    new_list = [item for item in base if item not in remove]
    print(new_list)
    

    在 Stack Overflow 帖子中 Remove list from list in Python 你有更多信息。

    【讨论】:

      【解决方案3】:
      inputList=[86.1, 86.2, 90.1, 90.2]
      
      tolerance=1.0
      out=[]
      for num in inputList:
          if all([abs(num-outAlready)>tolerance for outAlready in out]):
              out.append(num)
      
      print out
      

      【讨论】:

        猜你喜欢
        • 2019-03-22
        • 2014-11-29
        • 1970-01-01
        • 2023-01-09
        • 1970-01-01
        • 2021-03-15
        • 2020-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多