简体   繁体   中英

I'm having trouble with figuring out how the following code works?

Could someone please explain why ref_len = 9 after it runs, and how the second line in the code shown below works?

ref_len_list = [9,9,5,9]
ref_len = min(ref_len_list, key=lambda x:abs(x-8))

The line:

ref_len = min(ref_len_list, key=lambda x:abs(x-8))

will look for the number in ref_len_list for which abs(number - 8) has the lowest value, and thus is the value closest to 8 . From this list it gets the number 9 , because abs(9-8) < abs(5-8) . If there would be both 9 s and 7s in this list, it would just give the first one of those.

So:

min([9,9,5,9], key=lambda x:abs(x-8))  # --> 9
min([7,9,5,6], key=lambda x:abs(x-8))  # --> 7
min([9,7,5,6], key=lambda x:abs(x-8))  # --> 9
min([7,9,5,8], key=lambda x:abs(x-8))  # --> 8


The line works by using the min function and passing the optional key argument to it. The key argument will specify for the function what criteria it should use when ranking the elements of the list.

In this case the key argument is given an anonymous lambda function which will take a number x as an argument and return abs(x-8) .

The function lambda x:abs(x-8)) can be re-written as follows:

def func(x):
    return abs(x-8)

第二行代码ref_len = min(ref_len_list, key=lambda x:abs(x-8))仅查看第一行代码ref_len_list = [9,9,5,9]并找到最接近的值8.它只是从列表中选择一个满足代码的项目。

min picks the minimum value from the list. If given no key argument, it just uses the values themselves to determine what the "minimum" is (ie from a list of numbers it's somewhat obvious what the minimum is). Given a key argument, it uses that function to get the value for each item in the list that it should consider. It's typically mean for cases like this:

[{'foo': 3, 'bar': 'baz'}, {'foo': 4}]

min can't just know what value it should use here, so you'd do min(lst, key=lambda i: i['foo']) , which returns {'foo': 3, 'bar': 'baz'} , since it has the lowest value for i['foo'] ( 3 ). But key doesn't have to get a key from a dict, it can return any value it wants. Here it returns abs(x - 8) , so the result is the number whose value is the smallest when subtracted from 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM