📜  Python|列表元素的绝对值

📅  最后修改于: 2022-05-13 01:54:32.470000             🧑  作者: Mango

Python|列表元素的绝对值

有时,在使用Python列表时,我们需要找到绝对数,即列表中所有具有正数的元素。这个问题在数据科学的各个领域都有应用。让我们讨论一下可以完成此任务的某些方法。

方法 #1:使用列表理解 + abs()
可以使用列表理解技术执行此任务,其中我们只需迭代每个元素并使用abs()不断找到它的绝对值。

# Python3 code to demonstrate working of
# Absolute value of list elements
# using abs() + list comprehension
  
# initialize list
test_list = [5, -6, 7, -8, -10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Absolute value of list elements
# using abs() + list comprehension
res =  [abs(ele) for ele in test_list]
  
# printing result
print("Absolute value list : " + str(res))
输出 :
The original list is : [5, -6, 7, -8, -10]
Absolute value list : [5, 6, 7, 8, 10]

方法 #2:使用map() + abs()
此任务也可以使用map()执行。如上, map的任务就是执行将绝对数逻辑扩展到list中每个元素的任务。

# Python3 code to demonstrate working of
# Absolute value of list elements
# using map() + abs()
  
# initialize list
test_list = [5, -6, 7, -8, -10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Absolute value of list elements
# using map() + abs()
res = list(map(abs, test_list))
  
# printing result
print("Absolute value list : " + str(res))
输出 :
The original list is : [5, -6, 7, -8, -10]
Absolute value list : [5, 6, 7, 8, 10]