【发布时间】:2016-07-20 12:55:48
【问题描述】:
在如下所示的代码中编辑元组的推荐/最 Pythonic 方式是什么?
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 我同意。在这种情况下,速度不是问题。
标签: python python-2.7 tuples