这听起来像一个简单的问题。但是,鉴于:
a = [[(1,2)], [(3,4), (5,6)], [(7,8), (9,10), (11,12)]]
如何在元组中的每个第一项添加1,以便获得以下内容?
b = [[(2,2)], [(4,4), (6,6), [(8,8), (10,10), (12,12)]]
我尝试了如下代码:
b = []
for list_of_tuples in a:
for num1, num2 in list_of_tuples:
b.append((num1+1, num2))
b
但是,这破坏了原始结构。那么,我怎样才能得到我想要的东西,使用两个for循环?
答案 0 :(得分:4)
使用嵌套列表理解:
>>> a = [[(1,2)], [(3,4), (5,6)], [(7,8), (9,10), (11,12)]]
>>> b = [[(x+1, y) for x, y in tuples] for tuples in a]
>>> b
[[(2, 2)], [(4, 4), (6, 6)], [(8, 8), (10, 10), (12, 12)]]
作为具有列表理解的for
:
b = []
for tuples in a:
b.append([(x+1, y) for x, y in tuples])
没有任何列表理解:
b = []
for tuples in a:
tuples_b = []
for x, y in tuples:
tuples_b.append((x+1, y))
b.append(tuples_b)
答案 1 :(得分:1)
使用map()
和isinstance()
:
def func(x):
if isinstance(x,list):
return map(func,x)
elif isinstance(x,tuple):
return (x[0]+1,x[1])
a = [[(1,2)], [(3,4), (5,6)], [(7,8), (9,10), (11,12)]]
print map(func,a)
<强>输出:强>
[[(2, 2)], [(4, 4), (6, 6)], [(8, 8), (10, 10), (12, 12)]]
答案 2 :(得分:0)
您几乎正常,但您还需要先将元组的容器列表添加到b中,以重新创建原始结构
a = [[(1,2)], [(3,4), (5,6)], [(7,8), (9,10), (11,12)]]
b = []
for list_of_tuples in a:
b.append([])
for num1, num2 in list_of_tuples:
b[-1].append((num1+1, num2))
print b
输出:
[[(2, 2)], [(4, 4), (6, 6)], [(8, 8), (10, 10), (12, 12)]]
答案 3 :(得分:0)
你是否被元组困住了?将它们转换为列表可能会更好,因为您正在明确地修改它们。