简体   繁体   中英

how to find the element in a list whose value is closest to 0

Suppose I have a list,
x = [-7, 15, -6, -19, 27, 71, 3, -84, -16, -4, -15, -28, 18, 62, -93]
how to find the closest value to zero?

Use min() function with custom key:

x = [-7, 15, -6, -19, 27, 71, 3, -84, -16, -4, -15, -28, 18, 62, -93]

print(min(x, key=abs))

Prints:

3

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