【问题标题】:how can I get closest element from a list in python [duplicate]如何从python中的列表中获取最接近的元素[重复]
【发布时间】:2021-05-11 10:06:30
【问题描述】:

我有一个清单。 我想找出列表中的哪个数字在最高和最低之间最接近 k,但不使用 lambdaabs。我该怎么做?

a=[1,5,8,4,9,25,10,16,54]
k=12
highest = max(a)
lowest = min(a)

【问题讨论】:

  • 为什么是任意约束? abslambda 都是 python 的内置特性。
  • 对列表进行排序,然后使用线性搜索或二分搜索
  • @dawg bisect 与这些有什么关系?以及所有答案都使用abslambda 的问题如何被欺骗?

标签: python


【解决方案1】:
a=[1,5,8,4,9,25,10,16,54]
k=12


import sys

def func(lis, val):
    # minimum_difference is used to check the difference between value in list and key we have and it will keep record of minimum difference
    minimum_difference = sys.maxsize
    # nearest_value will save the list value for which we got minimum difference

    nearest_value = None
    # iterating through the list elements
    for i in lis:
        # getting the difference b/w key value and list element
        difference_key_element = val - i
        # checking if difference is neagtive or not, if negative make
        # it positive
        if difference_key_element<0:
            difference_key_element *= -1
        # checking if minimum value we find so far, is less then the 
        # current difference b/w key value and element value
        # if it is less then the current min value, replace it 
        # and store the list element in the store variable
        if difference_key_element<minimum_difference:
            minimum_difference=difference_key_element
            nearest_value = i
    # return the store variable
    return nearest_value

solution = func(a, k)
print(solution)

输出

10

【讨论】:

  • 这肯定会解决,但会使它变得更复杂。其实是想找点东西让孩子们看懂
  • @AtticRahman ADDED cmets,我认为这种线性方法是基本方法,您现在可以更轻松地解释它
【解决方案2】:

试试这个棘手的代码,

代码语法

for each in sorted(a):
    if each < k:
       lowest = each
    else:
        highest = each
        break

print(f"Original List: {a}\nLowest according to ({k}): {lowest}\nHighest according to ({k}): {highest}")

输出

Original List: [1, 5, 8, 4, 9, 25, 10, 16, 54]
Lowest according to (12): 10
Highest according to (12): 16

[Program finished]

【讨论】:

  • 列表也无法排序,这就是问题所在。
  • @AtticRahman 此解决方案将创建一个临时排序列表。原始列表不会排序。
  • 他/她没有提到任何关于排序的事情!
  • 谢谢你试试这个@Dr.Xavier
  • @Ted Klein Bergman,没错。我们不会在名单上玩。我们将整个列表图像指向另一个地址来操作它。但是我们没有改变主列表
猜你喜欢
  • 1970-01-01
  • 2020-09-07
  • 2017-12-06
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2020-12-17
  • 2022-07-09
  • 1970-01-01
相关资源
最近更新 更多