从Python中的元组中减去元组的元组?

时间:2013-04-28 23:50:58

标签: python tuples

我有一个元组元组:

nums = ((4, 5, 6), (5, 6, 7), (2, 3))

现在我想创建一个类似的结构,其中每个数字都从“基线”数字中减去。元组的基线数字是:

baselines = (1, 0.5, 3)

所以我想要的结构是:

# want: diffs = ((3, 4, 5), (4.5, 5.5, 6.5), (-1, 0))

我们有:

diffs[0] = [x - baselines[0] for x in nums[0]]
diffs[1] = [x - baselines[1] for x in nums[1]]
# etc.

如何在Python中优雅地完成这项工作?

2 个答案:

答案 0 :(得分:3)

zip与生成器表达式一起使用:

In [66]: nums = ((4, 5, 6), (5, 6, 7), (2, 3))

In [67]: baselines = (1, 0.5, 3)

In [68]: tuple( tuple( val-y for val in x ) for x,y in zip (nums,baselines ))
Out[68]: ((3, 4, 5), (4.5, 5.5, 6.5), (-1, 0))

答案 1 :(得分:0)

>>> [[x-baselines[i] for x in nums[i]] for i in range(3)]
[[3, 4, 5], [4.5, 5.5, 6.5], [-1, 0]]

你可以像这样制作元组

>>> tuple(tuple(x-baselines[i] for x in nums[i]) for i in range(3))
((3, 4, 5), (4.5, 5.5, 6.5), (-1, 0))