在如下所示的代码中编辑元组的一种推荐的/最蟒蛇的方式是什么?向一个元组中的所有值添加一个整数
tup_list = [(1, 2), (5, 0), (3, 3), (5, 4)]
max_tup = max(tup_list)
my_tup1 = (max_tup[0] + 1, max_tup[1] + 1)
my_tup2 = tuple(map(lambda x: x + 1, max_tup))
my_tup3 = max([(x+1, y+1) for (x, y) in tup_list])
以上三种方法哪一种是首选,还是有更好的方法来做到这一点? (在这个例子中当然应该返回(6, 5)
)。
有一种诱惑,像做
my_tup = max(tup_list)[:] + 1
或
my_tup = max(tup_list) + (1, 1)
但是没有这些工作的效果明显。
第一个看起来是最可读的。您还应该使用'timeit'模块来测试速度,我认为这会让结果更接近。 – Rockybilly
@Rockybilly我同意。在这种情况下,速度不是问题。 – Siwel