本文介绍了如何减去列表中的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含元组的列表.

Let's say I have a list with tuples in it.

类似这样的东西:

listnum = [(18,12),(12,20)]

有没有一种方法可以减去元组中的内容并将listnum变成:

Is there a way I can subtract what is in the tuples and make listnum into:

listnum = [6,8]

如您所见,它采用元组中最大的数字,然后将其相减.

As you can see It takes the biggest of the numbers in the tuple and subtracts it by the other.

推荐答案

使用列表理解:-

>>> listnum = [(18,12),(12,20)]
>>> [(i-j) for i,j in listnum]
[6, -8]
>>> listnum = [(18,12),(12,20),(32,54),(2,43)]
>>> [(i-j) for i,j in listnum]
[6, -8, -22, -41]

然后您要求输入bigger number - smaller;使用abs()进行计算.

And as you asked for bigger number - smaller; use abs() to calculate it.

>>> listnum = [(18,12),(12,20),(32,54),(2,43)]
>>> [abs(i-j) for i ,j in listnum]
[6, 8, 22, 41]

这篇关于如何减去列表中的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:39