Python - 更改列表中元组的元素符号


当需要更改元组列表中元素的符号时,可以使用一个简单的迭代、“abs”方法和“append”方法。

示例

下面演示了这个方法

Open Compiler
my_list = [(51, -11), (-24, -24), (11, 42), (-12, 45), (-45, 26), (-97, -4)] print("The list is :") print(my_list) my_result = [] for sub in my_list: my_result.append((abs(sub[0]), -abs(sub[1]))) print("The result is :") print(my_result)

输出

The list is :
[(51, -11), (-24, -24), (11, 42), (-12, 45), (-45, 26), (-97, -4)]
The result is :
[(51, -11), (24, -24), (11, -42), (12, -45), (45, -26), (97, -4)]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义一个元组列表,并在控制台中显示。

  • 定义一个空列表。

  • 对原始列表进行迭代。

  • 使用“abs”方法获取列表中负元素的绝对值。

  • 此结果附加到空列表。

  • 在控制台中显示为输出。

更新于: 15-Sep-2021

284 次浏览

开启您的职业

完成课程,获得认证

开始
广告