Python - 更改列表中元组元素的符号
给定一个双元组列表,任务是编写一个Python程序,将第二个元素转换为每个元组的负值,将第一个元素转换为每个元组的正值。
Input : test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
Output : [(3, -1), (4, -3), (1, -3), (2, -5), (4, -2), (9, -3)]
Explanation : All the first elements are positive, and 2nd index elements are negative, as desired.
Input : test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5)]
Output : [(3, -1), (4, -3), (1, -3), (2, -5)]
Explanation : All the first elements are positive, and 2nd index elements are negative, as desired.
方法 1:使用循环和abs()
在这种情况下,我们使用循环进行迭代,并使用 abs() 最初将两者转换为正数。第二个元素带有符号“-”,并根据需要转换为负元素。
例子:
Python3
# initializing lists
test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# 2nd element converted to negative magnitude
res.append((abs(sub[0]), -abs(sub[1])))
# printing result
print("Updated Tuple list : " + str(res))
Python3
# initializing lists
test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension used as one liner
res = [(abs(sub[0]), -abs(sub[1])) for sub in test_list]
# printing result
print("Updated Tuple list : " + str(res))
输出:
The original list is : [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
Updated Tuple list : [(3, -1), (4, -3), (1, -3), (2, -5), (4, -2), (9, -3)]
方法 2:使用列表理解
与上述方法类似,唯一的区别是使用列表理解作为一个 liner 来执行此任务。
例子:
蟒蛇3
# initializing lists
test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension used as one liner
res = [(abs(sub[0]), -abs(sub[1])) for sub in test_list]
# printing result
print("Updated Tuple list : " + str(res))
输出:
The original list is : [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
Updated Tuple list : [(3, -1), (4, -3), (1, -3), (2, -5), (4, -2), (9, -3)]