1

这听起来像是一个简单的问题。但是,给定一个:

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 循环呢?

4

4 回答 4

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)
于 2012-10-25T23:07:45.397 回答
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)]]
于 2012-10-25T23:19:57.030 回答
0

你被元组困住了吗?将它们转换为列表可能会更好,因为您显然正在修改它们。

于 2012-10-25T23:44:43.087 回答
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)]]
于 2012-10-25T23:07:22.853 回答