0

我有一个元组的元组:

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 中优雅地做到这一点?

4

2 回答 2

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))
于 2013-04-28T23:53:16.990 回答
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))
于 2013-04-29T00:11:05.377 回答