0

我有一个这样的清单

[(12,3,1),(12,3,5)]

和另外两个列表

 [4,2]

['A','B'] 

我想将这些添加到第一个列表中

[(12,3,4,'A',1),(12,3,2,'B',5)

他们必须处于这个位置,因为我计划删除元组中最后一个值为 1 的位置

4

2 回答 2

3

看,这里有一些魔法:

ts = [(12, 3, 1), (12, 3, 5)]
l1 = [4, 2]
l2 = ['A', 'B'] 
[t[:-1] + to_insert + t[-1:] for t, to_insert in zip(ts, zip(l1, l2))]
>> [(12, 3, 4, 'A', 1), (12, 3, 2, 'B', 5)]
于 2013-01-26T15:14:29.947 回答
1
def submerge(d, e, f):
    for g in d[:-1]:
        yield g
    yield e
    yield f
    yield d[-1] # if you want to remove the last element just remove this line

def merge(a, b, c):
    for d, e, f in zip(a, b, c):
        yield tuple(submerge(d, e, f))

a = [(12,3,1),(12,3,5)]
b = [4,2]
c = ['A','B'] 

print list(merge(a, b, c))
于 2013-01-26T15:20:04.617 回答